Manuel Costa
Manuel Costa

Reputation: 21

Windows forms and SQL cmd syntax error

Just want to use windows forms interface to insert data into the database. I think the code is right, but it is giving me an error saying "Incorrect syntax near the keyword 'User'."

image with tables names here

try
{
            string cmdString = @"insert into User (userName, userEmail, userBalance, userTickets) VALUES (@userName, @userEmail, @userBalance, @userTickets)" +
                                "insert into Account (accountName, accountPassword) VALUES (@accountName, @accountPassword)";

            // Connection 
            SqlConnection con = new SqlConnection("i dont know if is safe to show the con string...but i know its right");
            SqlCommand cmd = new SqlCommand(cmdString, con);
            con.Open();

            cmd.Parameters.Add("@userName", SqlDbType.NVarChar).Value = txtUserName.Text;
            cmd.Parameters.AddWithValue("@userEmail", SqlDbType.NVarChar).Value = txtemail.Text;
            cmd.Parameters.AddWithValue("@userBalance", SqlDbType.Money).Value = 100;
            cmd.Parameters.AddWithValue("@userTickets", SqlDbType.Int).Value = 3;
            //cmd.Parameters.AddWithValue("@accountID", null); 
            cmd.Parameters.AddWithValue("@accountName", SqlDbType.NVarChar).Value = txtUserName.Text;
            cmd.Parameters.AddWithValue("@accountPassword", SqlDbType.NVarChar).Value = txtPassword.Text;

            // Execute command
            cmd.ExecuteNonQuery();
            con.Close();
            //MessageBox.Show("Data saved!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

            Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

Can somebody give me a hand?

Upvotes: 0

Views: 28

Answers (1)

ChrisF
ChrisF

Reputation: 137178

User is a reserved word.

You need to enclose it in square brackets:

string cmdString = @"insert into [User] (userName, userEmail, userBalance, userTickets) VALUES (@userName, @userEmail, @userBalance, @userTickets)" +
                    "insert into Account (accountName, accountPassword) VALUES (@accountName, @accountPassword)";

Doing this will tell SQL to treat it as a table name and not the reserved word.

Upvotes: 1

Related Questions