Here is my Query:
string Select = "Update DC set Password = '" + txtPass.Text + "' WHERE ID ="+Convert.ToInt32(cbxDocs.SelectedIndex + 1);
con = new OleDbConnection();
this.readconfile = new ReadConfigFile();
con.ConnectionString = this.readconfile.ConfigString(ConfigFiles.ProjectConfigFile);
con.Open();
cmd = new OleDbCommand(Select, con);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
I don't know what is wrong but it gives me an error message that "Syntax error in UPDATE STATEMENT".
I have two fields in my table 'DC' ID and Password, nothing else.
PASSWORD is reserve word enclose it in square brackets like [Password], so your query should start like:
"Update DC set [Password]....
Consider using parameterized query, this will save you from Sql Injection
I think u don't need the ' on ur query and Password is reserved in almost every ddb.
And you could use parameters to avoid the concat with the +
Ex.
string pass = TxtPass.Text;
int s = cbxDocs.SelectedIndex+1;
string Select = "Update DC set Password = #a WHERE ID = #o";
OleDbCommand cmd = new OleDbCommand(Select, conn);
cmd.Paramaters.AddWithValue("#a", pass);
cmd.Parameters.AddWithValue("#o", s);
//everything else....
Related
I've looked at a lot of similar questions on this site and elsewhere but none of them have helped me.
I'm trying to make a database connection with a query but I get the error
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
on 2 different lines of code. I've tried to use spaces in the query around the = but that doesn't help.
Code 1 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NChar).Value = attackCategory;
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM attackCategory = #attackCategory WHERE TaughtOn = #taughtOn";
using (SqlDataAdapter sda = new SqlDataAdapter(select.CommandText, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
The exception is thrown on the sda.Fill(dt); line of code. This code works if no parameters are used in the query:
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
And code 2 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NVarChar).Value = attackCategory;
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Name FROM attackCategory = #attackCategory WHERE ID = #ID";
connection.Open();
object name = select.ExecuteScalar();
connection.Close();
return name;
The exception fires on the object name = select.ExecuteScalar(); line of code. This code works if 1 parameter is used in the query:
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Inhabitants FROM Planet WHERE ID=#ID";
You cannot provide table name has parameter, parameter applies in where clause with columns value.
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
but, we need to simplify to use parameter in this query.
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#taughtOn", SqlDbType.VarChar,50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
In the above tsql query, string concatenation applies and table name is included in the string, which will work.
Edit:-
I get it why you the sqlDataAdapter is not Recognizing the parameter.
Reason is you have not provided it. Yes, That's right you have provided the CommandText and not the Command Object which is of select variable.
I have corrected your code.
select.Parameters.Add("#taughtOn", SqlDbType.VarChar, 50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
select.Connection = new SqlConnection("provide your sql string");
using (SqlDataAdapter sda = new SqlDataAdapter(select))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Hope this helps !!
You can't bind object names like that. For object names, you'll have to resort to some sort of string concatenation. E.g.:
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM " + attackCategory + " WHERE TaughtOn=#taughtOn";
Note:
This is an over-simplified solution that does nothing to mitigate the risk of SQL-Injection attacks. You'll need to sanitize attackCategory before using it like this.
I am trying to make a simple memory game on visual Studio using C#. This game must keep some user records in the database. My database is not empty. This is part of my code :
string ConnectionString = #"Data Source =" + Application.StartupPath + #"\mydb.sdf";
SqlCeConnection sqlConnection1 = new SqlCeConnection(#"Data Source=" +Application.StartupPath + #"\mydb.sdf");
System.Data.SqlServerCe.SqlCeCommand cmdt = new System.Data.SqlServerCe.SqlCeCommand(ConnectionString);
cmdt.CommandText = "insert into logs (Sessionid, score, Minutes, Hintcount, Errorcount, Level, Picname) values(#ID, #Score, #Minutes, #Hintcount, #Errorcount, 'Level 1', #Picname)";
cmdt.Connection = sqlConnection1;
sqlConnection1.Open();
{
SqlCeCommand cmd = new SqlCeCommand("select ID from Userrecords where ID=(select MAX(ID) from Userrecords) and Username='" + LoginInfo.UserID + "'", sqlConnection1);
cmd.UpdatedRowSource = UpdateRowSource.OutputParameters;
int id = (int)cmd.ExecuteScalar();
cmdt.Parameters.AddWithValue("#Score", point);
cmdt.Parameters.AddWithValue("#Minutes", time);
cmdt.Parameters.AddWithValue("#Hintcount", hbuttoncount);
cmdt.Parameters.AddWithValue("#Errorcount", errorcount);
cmdt.Parameters.AddWithValue("#Picname", nameused2);
cmdt.Parameters.AddWithValue("#ID", id);
cmdt.UpdatedRowSource = UpdateRowSource.OutputParameters;
cmdt.ExecuteNonQuery();
sqlConnection1.Close();
}
I am trying to use executeScalar method, in order to retrieve the session ID from another table. But it always returns NULL, so it throws an exception. Is there any alternative that i can use?
I think you want the latest ID for this Username, then your query is wrong. Use:
var sql = #"SELECT MAX(ID) As Id
FROM Userrecords
WHERE Username = #UserName";
SqlCeCommand cmd = new SqlCeCommand(sql, sqlConnection1);
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = LoginInfo.UserID;
Your query returned the max-id if this record accidentially had the searched Username.
In an existing codebase there is hardcoded SQL and I want to avoid SQL injection.
The below code uses SqlCommand together with SqlParameters. The query does not return any data. However, when I remove the parameters the query returns the correct results.
How can I use SqlParameters with a SELECT statement?
string atUsername = "#username"; //does not work
//string atUsername = "Demo1"; //THIS WORKS
string atPassword = "#password"; //does not work
//string atPassword = "222"; //THIS WORKS
string sql = #"SELECT userId, userName, password, status, roleId, vendorId
FROM users
WHERE username = '" + atUsername + "' AND password = '" + atPassword + "'";
SqlCommand cmd = new SqlCommand(sql);
cmd.Parameters.Add(atUsername, SqlDbType.NVarChar, 20);
cmd.Parameters[atUsername].Value = "Demo1";
//cmd.Parameters.AddWithValue //also does not work
cmd.Parameters.Add(atPassword, SqlDbType.NVarChar, 20);
cmd.Parameters[atPassword].Value = "222";
//cmd.Parameters.AddWithValue //also does not work
SqlConnection conn = new SqlConnection(connStr);
cmd.Connection = conn;
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
Console.WriteLine(dt.Rows != null);
if (dt.Rows != null)
{
Console.WriteLine(dt.Rows.Count);
}
conn.Close();
conn.Dispose();
I have also unsuccessfully tried alternatives using
SqlCommand.ExecuteReader and SqlDataReader
IDisposable pattern
Replace cmd.Parameters.Add(atUsername with
SqlParameter pUsername = new SqlParameter();
pUsername.ParameterName = atUsername;
pUsername.Value = "Demo1";
cmd.Parameters.Add(pUsername);"
PS. I've heard of EntityFramework but I cannot use EF in this case (long story).
The root of your problem is that you use variable names inside string literal:
WHERE username = '#username' AND password = '#password'
So they are not treated as variable names by sql server. Instead you are searching for user with name "#username" and password "#password". Correct way is:
WHERE username = #username AND password = #password
con.Open();
string mysql; // generate an sql insert query for the database
mysql = "SELECT 1 FROM [Users] WHERE Username=? AND Password=?";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddWithValue("#p1", tbUser.Text);
cmd.Parameters.AddWithValue("#p2", tbPass.Text);
cmd.ExecuteNonQuery();
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if(temp==1)
{
Session["LogIn"] = lblUser.Text;
lblLogin.Text = "Welcome " + lblUser.Text + ", you are now logged in.";
}
else
{
lblLogin.Text = "Invalid Username/Password!";
}
con.Close();
Error: Syntax error in FROM clause.
"OleDbException was unhandled by user code."
Thanks.
EDIT
Now that I look closer there are many things wrong with this code. Standard practice is to check for the username/password combination in one shot:
mysql = "SELECT 1 FROM [User] WHERE UserName=? AND Password=?";
OleDbCommand CheckUser = new OleDbCommand(mysql, con);
// Add OleDbParameters here with the correct type/length
CheckUser.Parameters.Add("#userName", OleDbType.Char, 20).Value = tbUser.Text ;
CheckUser.Parameters.Add("#password", OleDbType.Char, 20).Value = tbPass.Text ;
int temp = Convert.ToInt32(CheckUser.ExecuteScalar().ToString());
and adding parameters to the command with the username and password values. That way hackers can't determine valid usernames without knowing the password.
This block:
mysql2 = "SELECT * FROM [User] WHERE Password='" + tbPass.Text + "'";
OleDbCommand Pass = new OleDbCommand(mysql2, con);
string Password = Pass.ExecuteScalar().ToString();
Will return the first column form the first row of the result set. Unless Password is the first column in the User table, you're not getting the password back, you're getting some other value.
It could be:
mysql2 = "SELECT password FROM [User] WHERE Password='" + tbPass.Text + "'";
OleDbCommand Pass = new OleDbCommand(mysql2, con);
string Password = Pass.ExecuteScalar().ToString();
First, just because it builds doesn't mean it's right.
Second, your code is vulnerable to SQL injection.
Third, without an error message or intent there's no way for us to divine what's wrong.
Last but not least: your code will only work if the first row of the first column obtained with the query returns a value of 1. I don't know what you're doing but if all else works for you, you may want to check that.
You can simply do it as :
con.Open();
string mysql; // generate an sql insert query for the database
mysql = "SELECT 1 FROM [Users] UserName='" + tbUser.Text + "' AND
Password='"+ tbPass.Text+"'";
OleDbCommand CheckUser = new OleDbCommand(mysql, con);
int temp = Convert.ToInt32(CheckUser.ExecuteScalar());
if(temp==1)
{
//Login
}
else
{
//Invalid UserName or Password.
}
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE(ID= '" +
txtStudentIDnumber.Text + "')";
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
In your command text you need to remove single quotes (') around the txtStudentIDnumber.Text as it appears ID is of type integer and you are passing it as string. Following should fix the error.
system.CommandText = "DELETE FROM Student WHERE(ID= " + txtStudentIDnumber.Text + ")";
EDIT: With respect to #mdb comments, you should always use Parameters in your query so that you can avoid SQL Injection. Consider the following:
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID = ?";
OleDbParameter parameter = new OleDbParameter("ID", txtStudentIDnumber.Text);
system.Parameters.Add(parameter);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID=#ID";
system.Parameters.AddWithValue("#ID", txtStudentIDnumber.Text);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
What will happen when user input for txtStudentIDNumber is,
1 or 1=1
In that case hardcoded SQL string will be,
DELETE FROM Student WHERE(ID=1 or 1=1)
So prefer parameterized sql statement instead of hard-coded string.
using(OleDbConnection cn=new OleDbConnection(cnStr))
{
using(OleDbCommand cmd=new OleDbCommand())
{
cmd.CommandText="DELETE FROM Student WHERE ID=#ID";
cmd.Connection=cn;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value=txtStudentIDnumber.Text;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}