I do want to pass StudName contents to my declared variable. i tried " +a.ToString+" But still i got errors
string a;
connection.Close();
connection.Open();
String strSQL = "select *from Students where StudName = '" +a.ToString() + "' and StudNum = '" + studentNumber;
OleDbCommand command = new OleDbCommand(strSQL);
StudNum = '" + studentNumber
The Database column for studentNumber is numeric but you're half treating it as alphanumeric.
Solution
StudNum = " + studentNumber
You need to use Parameterised commands to protect against an SQL Injection attack. This will also solve issues such as variables containing apostrophes and etc that would also cause your sql to fail.
Related
I am creating a program where you can store and change the balances of different accounts in visual C#. At the moment I am making the part where you can add to the balance of an account stored in a database to a table like this:
After adding on an amount of money, thus changing the currency, I want to be able to change the currency value in the database.
For example, if the current currency of an account (record) is £2. After adding on £3 I want to change the database so in the currency field for that record it now says £5.
I have written this code which is similar to how I inserted information into the database earlier in the code which worked successfully but I can't figure out how to use the syntax for the update command whilst using parameters in this context (doesn't work):
string sql = "update customers set balance values ('" + balance + "') where first_name values ('" + forename + "')";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
(This is the code I used earlier to insert information into the table that works):
string sql = "insert into leaders (ID, username, password, first_name, last_name) values (null,'" + username + "', '" + password + "', '" + first_name + "', '" + last_name + "')";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
You aren't using the correct syntax for update:
string sql = "update customers set balance = '" + balance + "' where first_name = '" + forename + "'";
Note that this is not a parameterized query, and might be vulnerable to SQL Injection attacks (or just break if one of the values contains a '). It's recommended to use a prepared statement with parameters:
string sql = "update customers set balance = #balance where first_name = #forename";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.AddWithValue("#balance", balance);
command.Parameters.AddWithValue("#forename", forename);
command.ExecuteNonQuery();
I am trying to push data into a column where the name is a variable.
From the code below:
label1.Text is the dynamic column of the DB database (it is a string)
ComboBox1.Text is the data that I want to put into the dynamic column (column name = label1.Text)
connection.Open();
OleDBCommand command = new OleDbCommand();
command.Connection = connection;
command.ConnectionText = "update DB set column1='" + richTextBox1.Text + "', " + label1.Text + " = '" + comboBox1.Text + "' where ID=" + label2.Text;
command.ExecuteNonQuery();
connection.Close();
I have tried many different things such as moving the single quotes and double quote locations, add the & sign for the string concatenation. But all I have been able to do is push the label1.Text, ComboBox1.Text, and richTextBox1.Text all into column1...
This is only a small portion of my code, so please let me know if you have questions.
I've been building a small inventory system for my workplace and have stumbled on an error that I cannot seem to fix
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
// "UPDATE Inventory SET Inventorynumber='"+ num +"',Inventory_Name='"+name+"', Quantity ='"+ quant+"',Location ='"+ location+"' Category ='"+ category+"' WHERE Inventorynumber ='"+ numquery +"';";
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "' Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = serverconnection;
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
I have no idea what to change here.
Any help would be appreciated.
Problem: You are missing the comma after location parameter in your query.
Solution: You need to separate the parameters using a comma.
Suggestion : Use parameterized queries to avoid SQL Injection Attacks.
Try this:
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
// "UPDATE Inventory SET Inventorynumber='"+ num +"',Inventory_Name='"+name+"', Quantity ='"+ quant+"',Location ='"+ location+"' Category ='"+ category+"' WHERE Inventorynumber ='"+ numquery +"';";
string query = "UPDATE Inventory SET Inventorynumber=#Inventorynumber,Inventory_Name=#Inventory_Name, Quantity =#Quantity ,Location =#Location,Category =#Category WHERE Inventorynumber =#Inventorynumber";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Inventorynumber",Convert.ToInt16(num));
cmd.Parameters.AddWithValue("#Inventory_Name",name);
cmd.Parameters.AddWithValue("#Quantity",quant);
cmd.Parameters.AddWithValue("#Location",location);
cmd.Parameters.AddWithValue("#Category",category);
cmd.Parameters.AddWithValue("#Inventorynumber",Convert.ToInt16(numquery));
cmd.Connection = serverconnection;
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
Yes the error is in the missing comma, but this is the result of all that mess with string concatenation that ends always in subtle syntax errors.
Why don't you use a parameterized query? It is a lot simpler to write and you avoid parsing errors like this and (more important) you avoid Sql Injections
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
string query = "UPDATE Inventory SET Inventorynumber=#num, Inventory_Name=#name, " +
"Quantity =#qty,Location =#loc, Category =#cat " +
"WHERE Inventorynumber =#numquery";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, serverconnection);
cmd.Parameters.AddWithValue("#num", Convert.ToInt16(num));
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#qty", quant);
cmd.Parameters.AddWithValue("#loc", location);
cmd.Parameters.AddWithValue("#cat", category);
cmd.Parameters.AddWithValue("#numquery", Convert.ToInt16(numquery));
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
As a side note I have some doubts about some parameters type. Are you sure that quantity is really a string as implied by the presence of quotes around your original value?
Also the numquery and num variables are of type string, you try to convert then to short integer and then you put them inside quotes (meaning that in the database the fields are of type text). This makes no sense at all. If the database expects numbers then do not use quotes, if the database expects strings then do not try to convert. Another reason to use a parameterized query that force you to reflect on these issues.
You are missing a Comma between location and category. You have heard this million times befor i know, but its really much better using prepared statements so you do not have to take care of this kind of things and your code is much more readable.
You missed the comma
Location ='" + location + "', Category ='" + category + "'
// see the `,` between Location and Category
you have missed comma(,) in query:
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "' Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
Make it as:
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "', Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
Try removing the ' single quotes around the integers?
I am writing a C# code that connects to ODAC. I think my query got no errors, but I get this error, I don't know how to solve.
This is my query
comm.CommandText = "SELECT * FROM ZAEDBA WHERE USER_ID = '" + login_id +
"' AND APPID = '" + app_id + "' ;";
Can any one figure out what is wrong in here?
Your query is vulnerable for a security issue called SQL injection!
You should NEVER use string concatenation for building a query from strings (some SQL, some parameters)... Use always parameterized queries...
Sample code:
comm.BindByName = true;
comm.CommandText = "SELECT * FROM ZAEDBA WHERE USER_ID = :login_id AND APPID = :app_id";
comm.Parameters.AddWithValue ("login_id", login_id);
comm.Parameters.AddWithValue ("app_id", app_id);
Why there is a ; in your sql command? Try this;
comm.CommandText = "SELECT * FROM ZAEDBA WHERE USER_ID = '" + login_id + "' AND APPID = '" + app_id "';
By the way, you should always use parameterized queries. This clearly open for an sql injection. For your query, use like this;
string commandText = "SELECT * FROM ZAEDBA WHERE USER_ID = #login_id " + AND
+ "WHERE APPID = #app_id;";
command.Parameters.Add("#login_id", SqlDbType.Int);
command.Parameters["#login_id"].Value = login_id;
command.Parameters.Add("#app_id", SqlDbType.Int);
command.Parameters["#app_id"].Value = app_id;
I'm having the error at the line: ins.ExecuteNonQuery().ToString(); OledDbException was unhandled Syntax error in INSERT INTO statement.
How do I fix this?
string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
string newTagID = textBox1.Text;
string newUser = textBox2.Text;
string newAge = textBox3.Text;
string newPhoneNumber = textBox4.Text;
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES ('" + newTagID + "', '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Connection.Open();
ins.ExecuteNonQuery().ToString();
ins.Connection.Close();
Your problem is probably one these three:
Outright syntax error not clearly visible with the hideous unparametrized SQL statement :p
newUser or some other field has a ' somewhere and is screwing up the syntax.
You are trying to insert a numeric value (Age?) as a string.
You should easily solve the first two creating a breakpoint after the insertString statement construction and checking out what the string really contains. The third one is even easier to check, just review the data types of the table's fields in your data base.
Notwithstanding, you should change the use of your command to use parameters and not build the query string with string concatenation (which is susceptible to sql injection attacks).
The issue is most likely because [Tag ID], User, Age, [Phone Number] are not all strings. In your SQL, any non-string column data should not be wrapped by quotes (').
To fix the immediate problem (assuming [Tag ID] is an integer):
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (" + newTagID + ", '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
However, you should structure your code to avoid sql injection, have cleaner code, and also not worry about the quotes:
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (#TagID, #User, #Age, #PhoneNumber)";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Parameters.Add(new OleDbParameter("#TagID",newTagID);
ins.Parameters.Add(new OleDbParameter("#User",newUser);
ins.Parameters.Add(new OleDbParameter("#Age",newAge);
ins.Parameters.Add(new OleDbParameter("#PhoneNumber",newPhoneNumber);
ins.Connection.Open();
ins.ExecuteNonQuery();
ins.Connection.Close();