0

I have a following code:

OleDbConnection aConnection = new
                    OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;
                                 Data Source=storage_db.accdb");
string sql = "INSERT INTO Client cname,phone,password)
                           VALUES('"+textBox1.Text+"','"+textBox2.Text+"',
                                  '"+textBox3.Text+"')";
aConnection.Open();
OleDbCommand insert = new OleDbCommand(sql, aConnection);
insert.ExecuteNonQuery();
aConnection.Close();

But when I try to insert data I am getting an exception syntax error in insert query. What am I doing wrong?

Our Man in Bananas
  • 5,809
  • 21
  • 91
  • 148
user3340565
  • 45
  • 1
  • 7

3 Answers3

2

Password is a reserved word in Access so you need to wrap the password column in square brackets in your query. You also need to wrap the columns you're inserting data into in parentheses:

INSERT INTO (Client cname,phone,[password]) VALUES(...

As @HarveySpecter points out in the comments you should also use a parameterized query rather than concatenating user input otherwise you're opening yourself up to SQL injection attacks.

petelids
  • 12,305
  • 3
  • 47
  • 57
1

Try this:

string sql = "INSERT INTO Client (cname, phone, [password])
VALUES('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"')";

You forget parentheses. But better use parameter queries.

Ella S.
  • 138
  • 1
  • 1
  • 7
  • And write here the result sql query from stack trace, for example `INSERT INTO Client (cname, phone, password) VALUES('text1','text2','text3'). Maybe error in your text data... – Ella S. May 21 '15 at 10:08
  • uncoat exception type "System.Data.OleDb.OleDbException" in System.Data.dll additional information: syntax error in INSERT INTO instruction. – user3340565 May 21 '15 at 10:11
  • What is Client table structure? All textboxes has values? – Ella S. May 21 '15 at 10:18
  • Yes texboxes all feeled/ Table client has 4 culumns id, cname, phone and password. id is autoincrement all other are type shorttext. – user3340565 May 21 '15 at 10:34
1

Your insert syntax is incorrect... you need to () around both the fields you are inserting AND the values clause...

insert into Client
   ( cname, phone, [password] )
   values
   ( ?, ?, ? )

The "?" are place-holders for the parameters and the parameter statements must be in the same order as the "?" represent. Also, note... if the values are expected to be numeric, date, etc, make sure the values you are setting in the parameter are the correct data type too. But in your case, these are all string-based.

OleDbCommand insert = new OleDbCommand(sql, aConnection);
insert.Parameters.Add( "parmName", textBox1.Text );
insert.Parameters.Add( "parmPhone", textBox2.Text );
insert.Parameters.Add( "parmPwd", textBox3.Text );
DRapp
  • 47,638
  • 12
  • 72
  • 142