0

I want to insert some data into SQL table. But while inserting int no matter what I've tried I get error:

System.Data.SqlClient.SqlException: 'Conversion failed when converting the varchar value '@ID' to data type int.'

I even manually set ID to 1 simply to be 100 % sure it's int but still get that error

String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar) 
VALUES ('@ID','@secondvar')";             
 using (SqlCommand cmd = new SqlCommand(query, connection))
                    {
                        int ID = 1;
                        cmd.Parameters.AddWithValue("@ID", ID);
                        cmd.Parameters.AddWithValue("@secondvar", tableModel.secondvar);    
                        connection.Open();
                        int result = cmd.ExecuteNonQuery();
0

2 Answers 2

5

Remove the quotes around the values. The framework handles that already.

VALUES ('@ID','@secondvar')

should be

VALUES (@ID,@secondvar)
Sign up to request clarification or add additional context in comments.

1 Comment

this answer is better, both values must be without semicolumns. I will mark this as answer after timeout elapse
1

ID is an integer so it must not be between '':

Change this line:

String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar) 
VALUES ('@ID','@secondvar')";

to this:

String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar) 
VALUES (@ID,@secondvar)";

And its better avoid using AddWithValue instead use it like:

String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar) 
VALUES (@ID,'@secondvar')";             
 using (SqlCommand cmd = new SqlCommand(query, connection))
 {
      int ID = 1;
      cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
      cmd.Parameters.Add("@secondvar", SqlDbType.VarChar).Value = somevalue; 
      //rest of the code
 }

1 Comment

Don't quote any values. Not even strings. The framework does that for you. That is the advantage of Prepared Statements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.