-2

I get syntax error when i try to run and insert data in my database.... i have a log in button and delete button that works just fine.... but this one does not and i don't get it..... Can some one tell me an alternative to insert or what is the mistake?

public partial class Register : Form
    {
        private OleDbConnection connect = new OleDbConnection();
        public Register()
        {
            InitializeComponent();
            connect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=resources\Users.accdb;
Persist Security Info=False;";
        }
    private void register1_Click(object sender, EventArgs e)
    {
        try
        {
            connect.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connect;
            command.CommandText ="insert into Users(Username, Password, Email)  values(' " + userR_box.Text + " ',' " + passwordR_box.Text + " ',' " + mailR_box.Text + " ')";
                            if ((userR_box.Text == "") || (passwordR_box.Text == "") || (mailR_box.Text == ""))
            {
                MessageBox.Show("Va rugam completati toate campurile");
            }
            else
            {
                command.ExecuteNonQuery();

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error "+ ex);
        }
        connect.Close();
    }
Mostafiz
  • 7,243
  • 3
  • 28
  • 42

2 Answers2

0

Firstly, read up on adding parameters to your query, on MSDN or Stack Overflow (How do parameterized queries help against SQL injection?).

It will save you building a string and maybe getting quotes in the wrong place.

Community
  • 1
  • 1
Peter Bill
  • 508
  • 3
  • 12
-1

Looking at your code i noticed 3 things:

  • You have extra space before every value ' " + userR_box.Text + " '
  • Its not clear what is the data that you are trying to insert, if it contains ' or any other char which might affect the query ... this will cause the error.
  • Password is reserved keyword, use this INSERT into Users ([Username], [Password], [Email]... to avoid reserved keywords.
Sufyan Jabr
  • 791
  • 4
  • 20