0

can someone tell me why when I insert into database this string 01-02-20070858430013, the result is -20070858430014

using (SqlConnection connection = new SqlConnection(con1))
        {
            connection.Open();
            for (int i = 0; i <= lb_dadosbrutos.Items.Count; i++)
            {
                using (SqlCommand command = new SqlCommand("INSERT INTO dbo.dados(Dados) VALUES(" + lb_dadosbrutos.Items[i] + ")", connection))
                {
                    //MessageBox.Show("INSERT INTO dbo.dados (Dados) VALUES (01-02-20070858430013)");// + range.Cells[i, 1].Value2.ToString() + ")");
                    command.ExecuteNonQuery();
                }
            }
        }

sry first stack question

Edit:

Tnks all, yes i missing the ' ', omg

msoeiro
  • 21
  • 1
  • 4
  • 4
    01 minus 02 minus 200708584300103 = -20070858430014 – jarlh Apr 30 '21 at 19:41
  • You want a string, `... VALUES ('01-02-20070858430013')` – jarlh Apr 30 '21 at 19:42
  • 3
    Also, consider [this](https://stackoverflow.com/questions/681583/sql-injection-on-insert). – ChiefTwoPencils Apr 30 '21 at 19:43
  • 2
    Never-never-never use string concatenation to compose sql queries! You have seen for yourself the danger of consequences. Use parameters instead. – Alexander Petrov Apr 30 '21 at 20:05
  • 3
    It's not the `'` you're missing, it's the correct use of parameterisation that you're missing! If you correctly use parameters, you don't even need to consider quote, it's taken care of for you. You're leaving yourself open to SQL Injection attacks and random failures if you ever need to insert values with quotes or other special characters. Use parameterisation!!! – MatBailie Apr 30 '21 at 20:20

2 Answers2

0

I think you are trying to store this value as a string but your code is storing as integer.

so your query is suppose to have this following query with this 01-02-20070858430013 quoted in a string before been placed in a values.

("INSERT INTO dbo.dados (Dados) VALUES ('01-02-20070858430013')")
-2

Check you Table design. You may set column type as Int.Change it to nvarchar

  • 2
    Even if the table column is an NVARCHAR, the expression `01-02-20070858430013` ***isn't***. The expression would ***still*** be resolved first, ***then*** the result of that expression *(`-20070858430014`)* would be implicitly coerced to string and inserted in to the table. This answer is back to front and upside down *(aka, wrong)*. – MatBailie Apr 30 '21 at 20:14