我是C#的新手,我想在Access中插入一些Datagridview列,以便以后检索这些数据。
private void metroButton5_Click(object sender, EventArgs e)
try
{
OleDbConnection connection = new OleDbConnection(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\Database\DBAdatabase.accdb; Persist Security Info = False; ");
for (int s = 0; s < dataGridView1.Rows.Count - 1; s++)
{
OleDbCommand command = new OleDbCommand(@"INSERT INTO Quotations (Position, LVPosition)VALUES('"+dataGridView1.Rows[s].Cells[0].Value+"','"+dataGridView1.Rows[s].Cells[1].Value+"')", connection);
connection.Open();
command.Connection = connection;
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
我变成“错误Systen.Data.OleDb.OleDbException(0x80040E14):插入错误中的语法错误”。
有人可以帮我解决吗.....
非常感谢。
我也提到了此链接(https://www.youtube.com/watch?v=8hCfje5VL-0&ab_channel=codefactory2016),但是我找不到错误原因。
答案 0 :(得分:0)
立即改变,我会改变
MessageBox.Show("Error " + ex);
到
MessageBox.Show("Error " + ex.Message);
它将使您对错误有更好的了解
此外,使用参数也是一种很好的做法,它可以防止单引号问题并防止sql注入问题:
try
{
OleDbConnection connection = new OleDbConnection(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\Database\DBAdatabase.accdb; Persist Security Info = False; ");
OleDbCommand command = new OleDbCommand("", connection);
for (int s = 0; s < dataGridView1.Rows.Count - 1; s++)
{
command.Parameters.AddWithValue("@position",dataGridView1.Rows[s].Cells[0].Value);
command.Parameters.AddWithValue("@lvPosition",dataGridView1.Rows[s].Cells[1].Value);
command.CommandText = "INSERT INTO Quotations (Position, LVPosition) VALUES (@position, @lvPosition)";
connection.Open();
//this line is not needed as it is set in the command constructor above
//command.Connection = connection;
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
connection.Close();
//edit - this needs to run or you will have duplicate values inserted
command.Parameters.Clear();
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex.Message);
}
即使如此,我仍然会认真考虑对连接和命令使用语句,并尝试尝试打开连接。但这有点离题