我必须使用insert query在表中插入值...存储在数据库中的表有3列:1。Date(DateTime)2。SensorValue(Float)3。差异(Float) 现在每列的值来自datagridview .....这里是插入按钮的代码
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");
执行查询时出错... ....日期列中的第一个条目是值:12/05/2012 14:32:00 ....所以基本上sql不接受冒号放在14 ....我怎么能解决这个问题?请帮忙
答案 0 :(得分: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,参数更安全。
答案 1 :(得分:2)
该代码甚至无法编译,因此无法给出运行时错误。
这里你的引号太多了:
String query1 = "INSERT INTO " + tbName + " (" Date, Sensor...
应该是:
String query1 = "INSERT INTO " + tbName + " ( Date, Sensor...
当你有一个日期时间值时,你需要它周围的撇号:
...LUES (" + dataGridView1.Rows[i].Cells[0].Value + "," + ...
应该是:
...LUES ('" + dataGridView1.Rows[i].Cells[0].Value + "'," + ...
答案 2 :(得分: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();
}
答案 3 :(得分:0)
虽然我很难推荐使用参数,但是在没有看到所有变量的情况下很难诊断出来。它不仅会使这类问题更容易被发现,而且还可以保护您免受SQL注入攻击。