我想用datagridview中的数据填充本地访问数据库。我已经将数据库添加到项目中,它的使用仅限本地。我已经复制了连接字符串并建立了将数据传递到访问表的查询。我正在从另一个ViewForm1输入数据,因此在向其中添加数据时我不访问数据库。
我构建项目,导航到表单,将数据写入表,然后按添加。结果是:
System.Data.OleDb.OleDbException:“插入到Anweisung中的语法。”迪瑟·奥斯纳姆(Diese Ausnahme)乌尔·乌斯普伦格(Wurdeursprünglich)北迪塞尔System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(System.Data.OleDb.OleDbHResult)System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(System.Data.OleDb.tagDBPARAMS,输出对象)System.Data.OleDb.OleDbCommand.ExecuteCommandText(输出对象)System.Data.OleDb.OleDbCommand.ExecuteCommand(System.Data.CommandBehavior,out对象)System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(System.Data.CommandBehavior,字符串)System.Data.OleDb.OleDbCommand.ExecuteNonQuery()databasecontrol.cs中的vdefinder.databasecontrol.addToTableBtn_Click(object,System.EventArgs)System.Windows.Forms.Control.OnClick(System.EventArgs)System.Windows.Forms.Button.OnClick(System.EventArgs)System.Windows.Forms.Button.OnMouseUp(System.Windows.Forms.MouseEventArgs)...[Aufrufliste abgeschnitten]
如果我不向datagridviewcell输入任何内容-按下添加按钮时没有错误出现。
using System.Windows.Forms;
using System.Data.OleDb;
namespace vdefinder
{
public partial class databasecontrol : Form
{
public databasecontrol()
{
InitializeComponent();
}
private void backToLoginBtn_Click(object sender, EventArgs e)
{
Hide();
login li = new login();
li.ShowDialog();
}
private void addToTableBtn_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\_VS_Projekte\vdefinder\vdefinder\vdefinder.mdb;Persist Security Info=True");
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
OleDbCommand cmd = new OleDbCommand(@"INSERT INTO vdefinder (Index, Kategorie, Inhalt) VALUES ('" + dataGridView1.Rows[i].Cells[0].Value + "', '"+dataGridView1.Rows[i].Cells[1].Value+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved to table.");
}
dataGridView1.Rows.Clear();
}
}
}
错误与insert语句语法有关。您可能要检查下面一行的传递参数:
OleDbCommand cmd = new OleDbCommand(@"INSERT INTO vdefinder (Index, Kategorie, Inhalt) VALUES ('" + dataGridView1.Rows[i].Cells[0].Value + "', '"+dataGridView1.Rows[i].Cells[1].Value+"')", con);
我相信您只有2个值,而实际上Index,Kategorie和Inhalt需要3个值。