0

Edit: I now see the similarities. Thank you for the question to reference.

I am trying to insert a new row into a test table where the id column is a uniqueidentifier. I have generated a guid (userID) however, it will not pass along into SQL. I always get the error "syntax error around "

Is it my syntax of how I entered userID into the SQL query or am I just going about this completely the wrong way.

I have the following code:

            cnn = new SqlConnection(connectionString);
            cnn.Open();
            Guid userID = Guid.NewGuid();

            string sql;
            sql = "INSERT INTO test (id, column1, column2) VALUES ("+@userID+",222,333)";
            command = new SqlCommand(sql, cnn);
            try
            {
                command.ExecuteNonQuery();
                MessageBox.Show("success!");
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
Mikael
  • 1,002
  • 1
  • 11
  • 22
  • `VALUES ("+@userID+"`should be `VALUES (@userID`. Then read the duplicate to see how to pass the parameter. – mjwills Sep 26 '19 at 00:59
  • I think you want: `sql = "INSERT INTO test (id, column1, column2) VALUES ('"+@userID+"',222,333)";` -- Note the quotes around the GUID.. – Mike Christensen Sep 26 '19 at 01:18
  • 5
    Do **not** do what @MikeChristensen has said. This is a bad habit to get into (it will work in this instance, but bite you later when you use the same technique for strings). Use parameters **always**, as per the duplicate. – mjwills Sep 26 '19 at 01:19
  • Also I think people want you to read the dupe since it shows the correct way to pass in parameters. They are correct and will claim this protects you against SQL injection accounts. Your _particular_ example isn't prone to SQL injection due to the data type, but using parameterized queries is a good habit to get into nonetheless. – Mike Christensen Sep 26 '19 at 01:20

0 Answers0