executenonquery() error c#
this is how my code looks like
con.Open();
String name = textBox1.Text.ToString();
String address = textBox2.Text.ToString();
String id = textBox3.Text.ToString();
int iid = Int32.Parse(id);
String semester = textBox4.Text.ToString();
int i_sem = Int32.Parse(semester);
String field = comboBox1.SelectedItem.ToString();
String qry = "insert into Table values('" + name + "','" + address + "'," + iid + "," + i_sem + ",'" + field + "',)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.ExecuteNonQuery();
executenonquery() always makes me problem !
int i = cmd.ExecuteNonQuery();
You need to fix a couple of things:
Remove the last , in your query.
I don't know if you have a table named Table in your database but you should check if the name is correct.
When you don't know how to correct your code it's better use the try-catch statement to understand where the real problem is in your code. Here is an example about how to handle SQL exception in C# code.
You are getting SqlException because your query syntax is wrong but there is another way to add SQL parameters into your query without need to use a string variable. You could use the SqlParameterCollection.AddWithValue(String, Object) method to achieve the same result and avoid SQL Injection:
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT into YourTableName (name, address, id, semester, field) VALUES (#name, #address, #id, #semester, #field)";
command.Parameters.AddWithValue("#name", name);
command.Parameters.AddWithValue("#address", address);
command.Parameters.AddWithValue("#id", iid);
command.Parameters.AddWithValue("#semester", i_sem);
command.Parameters.AddWithValue("#field", field);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
// error here
}
finally
{
connection.Close(); //close your connection if you do not need to keep it open
}
More info:
AddWithValue Method
SQL Injection
Other examples related to this topic
Related
I'm making a form on C# that inserts data in a table with a where clause, but it's not working. I think the syntax of my query is the problem but I can't solve it.
This is the one that I tried that's working, but I need an insert query with a where clause.
SqlCommand addEmp = new SqlCommand("INSERT INTO tbl_Expenses " +
"(InvestedMoney,EstimatedServingCount,MealName) " +
"VALUES (#inv, #est, #mname)", conn);
addEmp.Parameters.AddWithValue("#mname", textBox1.Text);
addEmp.Parameters.AddWithValue("#inv", textBox2.Text);
addEmp.Parameters.AddWithValue("#est", textBox3.Text);
conn.Open();
addEmp.ExecuteNonQuery();
conn.Close();
I tried this code below:
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_Meal" +
" ExpensesID, MealName, MealPrice, ImageName, Imageblob)" +
"SELECT ExpensesID, #mname, #mprice, #imname, #img " +
"FROM tbl_Expenses" +
"WHERE MealName = '"+textBox1.Text+"'",conn);
cmd.Parameters.AddWithValue("#mname", textBox1.Text);
cmd.Parameters.AddWithValue("#mprice", textBox4.Text);
cmd.Parameters.AddWithValue("#imname", textBox1.Text);
cmd.Parameters.Add("#img", SqlDbType.Image, photo.Length).Value = photo;
conn.Open();
cmd.ExecuteNonQuery();
But I get this error:
System.Data.SqlClient.SqlException: Incorrect syntax near '='
This section is missing a space between the lines:
"from tbl_Expenses" +
"WHERE MealName = '"
so the sql code references a table named tbl_ExpensesWHERE, gives the table an alias of MealName, and then has an out-of-place =.
But you should also already know from the use of parameters elsewhere it is NOT okay to substitute textBox1.Text into the query like that. NEVER do that. Not even once. Not even for practice/learning code!
There are some other poor practices in here, but that was the worst. Here's a better pattern:
string sql = #"
INSERT into tbl_Meal
(ExpensesID,MealName,MealPrice,ImageName,Imageblob)
SELECT
ExpensesID,#mname,#mprice,#mname,#img
FROM tbl_Expenses
WHERE MealName = #mname";
using (var conn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, conn))
{
//wild guess at column types. Use actual column types/size FROM THE DATABASE
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 30).Value = textBox1.Text;
cmd.Parameters.Add("#mprice", SQlDbType.Decimal, 18, 8).Value = textBox4.Text;
//use the size of the column here, not the length of the photo
cmd.Parameters.Add("#img", SqlDbType.Image, 8000).Value = photo;
conn.Open();
cmd.ExecuteNonQuery();
}
Instead of Parameters.AddWithValue() use Parameters.Add() and also use correct datatypes, for example EstimatedServingCount seems to be an int, but however AddWithValue can not know that:
addEmp.Parameters.Add("#mname", SqlDbType.VarChar).Value = textBox1.Text;
addEmp.Parameters.Add("#inv", SqlDbType.VarChar).Value = textBox2.Text;
addEmp.Parameters.Add("#est", SqlDbType.Int).Value = textBox3.Text;
These are the two set up tables
LOGIN TABLE
USER'S NAME
I want to create something like the User will key in their USER_ID and USER_PWD in a textbox. IF the user successfully login, it will say " HI + PATNAME ".
I have created this code so far but it isnt working.
string sqlStr = "Select patpro.'PATNAME' FROM patpro,useform where USER_ID=#name and USER_PWD=#password and useform.'USER_ID' = patpro.'USERID'";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Password);
cmd.CommandText = sqlStr;
cmd.Connection = connection;
connection.Open();
MySqlDataReader login = cmd.ExecuteReader();
if (login.HasRows)
{
login.Read();
string name = (login["USER_ID"].ToString());
txtAssignID1.Text = "Login verified. Hi, " + name + "\n";
}
From what I see, you're trying to use login["USER_ID"].ToString() which USER_ID is a nonexistent column definition inside current SELECT statement. Hence, you should add column names which defined in SELECT results like login["PATNAME"] and use proper INNER JOIN statement instead:
string sqlStr = #"SELECT patpro.PATNAME FROM patpro INNER JOIN useform
ON useform.USER_ID = patpro.USERID
WHERE useform.USER_ID = #name AND useform.USER_PWD = #password";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Password);
cmd.CommandText = sqlStr;
cmd.Connection = connection;
connection.Open();
MySqlDataReader login = cmd.ExecuteReader();
if (login.HasRows)
{
// read value inside the loop, because MySqlDataReader is forward-only
while (login.Read())
{
string name = login["PATNAME"].ToString();
txtAssignID1.Text = "Login verified. Hi, " + name + "\n";
}
}
Additional note: Better to use using statement for MySqlConnection, MySqlCommand and MySqlDataReader to ensure immediate disposal of MySQL connection objects after fetching query results.
I get this error when I try to add a new person to my listbox and into my database.
My code:
public void AddSpeler(string name, string club)
{
conn.Open();
Speler speler = new Speler();
speler.Name = name;
speler.Club = club;
string query = "INSERT INTO Speler OUTPUT Inserted.ID VALUES ('" + speler.Name + "', '" + speler.Club + "')";
SqlCommand cmd = new SqlCommand(query, conn);
speler.ID = (int)cmd.ExecuteScalar();
conn.Close();
}
I get the error on the part:
"speler.ID = (int)cmd.ExecuteScalar();
And yes, I have my primary key (ID) set to increase by one.
As said in the comment above, you shouldn't write an sql command concatenating strings. This is well known to be a source of bugs and a big security risk called Sql Injection.
The second point to fix is the syntax used. In an INSERT INTO statement you should provide the column that matches the values inserted. If you don't supply the column names then you need to write the values for each column in the table and in the exact order in which the columns are defined
void AddSpeler(string name, string club)
{
conn.Open();
Speler speler = new Speler();
speler.Name = name;
speler.Club = club;
string query = #"INSERT INTO Speler (Name, Club) OUTPUT Inserted.ID
VALUES (#name, #club)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = speler.Name;
cmd.Parameters.Add("#club", SqlDbType.NVarChar).Value = speler.Club;
speler.ID = (int)cmd.ExecuteScalar();
conn.Close();
}
Here I assume that your table Speler contains the columns named Name and Club, of course change them to your actual names.
EDIT
If you want to call this method from another class, you need to make it public so every callers that creates an instance of the class where the method is defined can use it.
By the way, the code in AddSpeler does some things that are wasted if you don't return them to your caller (void ??) Possibly you want to return the instance of the Speler class created in the code so change the method to
public Speler AddSpeler(string name, string club)
{
try
{
conn.Open();
Speler speler = new Speler();
.....
....
return speler;
}
catch(Exception ex)
{
// display the ex.Message to know why your code fails
MessageBox.Show(ex.Message);
conn.Close();
return null; // no Speler returned if code fails
}
}
The problem is that you want to skip the ID column in the values provided, so you need to specify that.
string query = "INSERT Speler (Name, Club) OUTPUT Inserted.ID VALUES ('" + speler.Name + "', '" + speler.Club + "')";
While this will solve the error, you should absolutely not concatenate SQL strings! Use parameters instead.
Why my code show this message
Data type mismatch in criteria expression.
The attribute Fine is in number datatype.
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string cq = "select sum(Fine) from Studentbook where Student_ID='" + textsearch.Text + "'";
command.CommandText = cq;
int a = Convert.ToInt32(command.ExecuteScalar());
connection.Close();
MessageBox.Show(a.ToString(), "Your FINE is", MessageBoxButtons.OK);
Other than possible SQL Injection vulnerability; the said error could be because of the WHERE part in your query; where Student_ID is number and you are trying to compare it with string type data.
where Student_ID='" + textsearch.Text + "'"
Considering that your Student_ID is of INT or NUMBER type column change your code to be like below. Notice the use of parameterized query to avoid SQL Injection
string sql = "select sum(Fine) from Studentbook where Student_ID = #studentid";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#studentid", Convert.ToInt32(textsearch.Text.Trim()));
So I created and invoked a WCF service in C#, but keep getting a false back, I am unsure as to why it is. It might be to do with the connection string but changing it from the current just gives me errors.
Here's my code:
//Create the new connection
SqlConnection myConnection = new SqlConnection();
//Create the query
String myQuery = "INSERT INTO Player (registrationID, firstName, lastName, phoneNumber, Address, dateOfBirth) " +
" VALUES ('" + registrationID + "', '" + firstName + "', '" + lastName + "', '" + phoneNumber + "', '" + Address + "', '" + dateOfBirth + "');";
//The connectionString can be found in the properties table of the database
myConnection.ConnectionString = "Data Source=C:/Users/User/Documents/Visual Studio 2012/Projects/ADO_LINQ/ADO_LINQ/App_Data/MyDatabase.sdf";
//Initialuze the command
SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
SqlDataReader myReader;
//Run the command
try
{
myConnection.Open();
myReader = myCommand.ExecuteReader();
//Return true if it was successful
return true;
}
catch (Exception ex)
{
return false;
}
As Soner pointed out, your code is susceptible to SQL Injection attacks, and this can be remedied by using parameterized queries. Also, best practice is to use a using block with the connection so it is properly closed and disposed of once the code in the using block is exited (currently you're not even closing the connection when you're done).
Also, ExecuteNonQuery is sufficient for this - it will run the command and then return the number of rows affected (which should be 1 in this case). You can check the number of rows affected and use that to determine success/failure, in addition to using a catch block in the case of an exception. Realistically I would not expect anything other than the value of 1 unless an exception was thrown while executing the command.
Finally your posted code is swallowing the exception. You should do something with the exception (log it, execute some other code, rethrow it - depending on the requirements of your app) rather than simply returning false.
Putting it all together:
using (SqlConnection myConnection = new SqlConnection())
{
// Create the query
String myQuery = "INSERT INTO Player (registrationID, firstName, lastName, phoneNumber, Address, dateOfBirth) " +
" VALUES (#RegistrationID, #FirstName, #LastName, #PhoneNumber, #Address, #DateOfBirth)";
//The connectionString can be found in the properties table of the database
myConnection.ConnectionString = "Data Source=C:/Users/User/Documents/Visual Studio 2012/Projects/ADO_LINQ/ADO_LINQ/App_Data/MyDatabase.sdf";
//Initialuze the command
SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
myCommand.CommandType = CommandType.Text;
// Here you add the values for the parameters in the query
myCommand.Parameters.Add("#RegistrationID", SqlDbType.VarChar).Value = registrationID;
myCommand.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = firstName;
myCommand.Parameters.Add("#LastName", SqlDbType.VarChar).Value = lastName;
myCommand.Parameters.Add("#PhoneNumber", SqlDbType.VarChar).Value = phoneNumber;
myCommand.Parameters.Add("#Address", SqlDbType.VarChar).Value = address;
myCommand.Parameters.Add("#DateOfBirth", SqlDbType.VarChar).Value = dateOfBirth;
//Run the command
try
{
myConnection.Open();
int rowsAffected = myCommand.ExecuteNonQuery();
if (rowsAffected == 1)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
// Do something with the exception, like logging it so you can review the error
return false;
}
}
The above code wraps the call in a using statement. When the command is created, the parameters are added to the SqlCommand.Parameters collection, and then ExecuteNonQuery is returned. If the result is 1, true is returned, otherwise false is returned. If an error is encountered, false is returned but again you should do something with the exception so you can troubleshoot if needed.