Click here to Skip to main content
15,890,186 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
static OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["dbProject"].ConnectionString);




Im getting SQL syntax error when executing the query.
C#
public static void InsertLogins(User u)
      {
          conn.Open();
          OleDbCommand cmd = new OleDbCommand("Insert into tblLogin(Username,Password,CharPreset) values ('" + u.Username + "','" + u.Password + "','" + u.CharPreset + "')", conn);

          cmd.ExecuteNonQuery();

          conn.Close();

      }



I can read from the database using this query
C#
OleDbCommand cmd = new OleDbCommand("Select * From tblLogin", conn);


What I have tried:

Everything I could think of. It works when using SQL server but I want it to work with Microsoft Access
Posted
Updated 17-May-18 9:36am
v2
Comments
Richard MacCutchan 17-May-18 15:09pm    
And please don't tell us you are storing passwords in clear text.
[no name] 17-May-18 15:11pm    
Just because a "select" works, doesn't mean an "insert" will.

"Hard code" your insert until it works; THEN "parameterize" it.

First, Google for "SQL Injection Attack" to find out why what you're doing is so bad.

Next, Google for "C# sql parameterized queries" to find out how to solve that problem and the problem you're running into.
 
Share this answer
 
Some light reading for you:
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]


And:
Secure Password Authentication Explained Simply[^]
Salted Password Hashing - Doing it Right[^]


An immediate fix for the SQLi vulnerability:
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO tblLogin (Username, Password, CharPreset) VALUES (?, ?, ?)", conn))
{
    cmd.Parameters.AddWithValue("p0", u.Username);
    cmd.Parameters.AddWithValue("p1", u.Password);
    cmd.Parameters.AddWithValue("p2", u.CharPreset);
    
    cmd.ExecuteNonQuery();
}

But don't ignore the password storage problem!

Oh, and storing the connection object in a static field is a terrible idea, especially if this is a web application. Connections are not thread-safe, and if two requests hit at the same time, the best you can hope for is a crash.
 
Share this answer
 
v2
Comments
Member 12462239 19-May-18 7:07am    
Hey did what you said and used your code but still getting syntax error when Executing the query. I have a feeling its because Im using Microsoft Access

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900