2012-11-23 97 views
2

我必须插入使用插入查询表中的值...存储在数据库中的表有3列:1.日期(日期时间)2. SensorValue(浮动)3,差异(浮动) 现在每列的值来自datagridview的.....这里是按钮的插入错误:附近有语法错误“14”

con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\dbsave.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; 
if (con.State == ConnectionState.Closed) 
{ 
    con.Open(); 
} 
for (Int32 i = 0; i < dataGridView1.Rows.Count-1; i++) 
{ 
    String query1 = 
     "INSERT INTO " + tbName + 
     " (Date, SensorValue, Difference) " + "VALUES (" +  
     dataGridView1.Rows[i].Cells[0].Value + "," + 
     dataGridView1.Rows[i].Cells[1].Value + "," + 
     dataGridView1.Rows[i].Cells[2].Value + ")"; 
    SqlCommand cmd1 = new SqlCommand(query1, con); 
    cmd1.ExecuteNonQuery(); 
} 
con.Close(); 
MessageBox.Show("The table has been saved"); 

代码中的错误是ofcourse查询的执行....在第一项日期列是价值:2012年12月5日14:32:00 ....所以基本上SQL是不接受与14放置的结肠....我怎么能解决这个问题?请帮助

+3

请去研究参数化查询 - 它们避免了将所有内容都转换为字符串的问题。 –

+0

这些列的数据类型是什么? –

+0

请使用DBParameter!它会使你的查询字符串更具可读性,并且可以帮助你避免很多错误! – igrimpe

回答

5

更新您的查询,添加撇号:

String query1 = 
    "INSERT INTO " + tbName + 
    " (Date, SensorValue, Difference) " + "VALUES ('" +  
    dataGridView1.Rows[i].Cells[0].Value + "'," + 
    dataGridView1.Rows[i].Cells[1].Value + "," + 
    dataGridView1.Rows[i].Cells[2].Value + ")"; 
SqlCommand cmd1 = new SqlCommand(query1, con); 

但我Liath同意,参数更安全。

+0

它的工作....感谢üSOOO多:) – Tushar

+0

下一次我会用参数) – Tushar

0

没有看到它的所有难以诊断的变量,虽然我严重推荐使用的参数。它不仅会使这类问题更容易被发现,而且还会保护您免受SQL注入攻击。

2

该代码甚至不进行编译,所以也不能给出一个运行时错误。

你有一个引号太多的位置:

String query1 = "INSERT INTO " + tbName + " (" Date, Sensor... 

应该是:

String query1 = "INSERT INTO " + tbName + " (Date, Sensor... 

当你有一个datetime值,则需要撇号周围:

...LUES (" + dataGridView1.Rows[i].Cells[0].Value + "," + ... 

应该是:

...LUES ('" + dataGridView1.Rows[i].Cells[0].Value + "'," + ... 
2

尝试使用参数化查询。像这样:

string query = "INSERT INTO table (Date, SensorValue, Differences) VALUES (@Date, @SensorValue, @Differences)";    
var command = new SqlCommand(query, con); 
command.Parameters.Add(new SqlParameter("@Date", System.Data.SqlDbType.DateTime)); 
command.Parameters.Add(new SqlParameter("@SensorValue", System.Data.SqlDbType.Float)); 
command.Parameters.Add(new SqlParameter("@Differences", System.Data.SqlDbType.Float)); 
for (int i = 0; i < dataGridView1.Rows.Count-1; i++) 
{ 
    command.Parameters["@Date"].Value = Convert.ToDateTime(dataGridView1.Rows[i].Cells[0].Value); 
    command.Parameters["@SensorValue"].Value = Convert.ToDecimal(dataGridView1.Rows[i].Cells[1].Value); 
    command.Parameters["@Differences"].Value = Convert.ToDecimal(dataGridView1.Rows[i].Cells[2].Value); 
    command.ExecuteNonQuery(); 
} 
+0

了... ... .thanx :) – Tushar

+0

对于参数为+1,但请不要在循环中清除并重新添加,但要添加到循环外部,然后仅将vales赋值给(然后!)现有参数。 – igrimpe

+0

你是对的,改变了它。 –