[英]Access database and C# issues with auto increment primary key
我有一個名字,姓氏,電子郵件,主管的表格。 然后將按鈕上的代碼設置為此
private void agentInsertButton_Click(object sender, EventArgs e)
{
try
{
ad.InsertCommand = new OleDbCommand("insert into Agents values ([FirstName],[LastName],[Email],[Supervisor])", con);
ad.InsertCommand.Parameters.Add("@FirstName", OleDbType.VarChar).Value = agentNametextBox1.Text.ToString();
ad.InsertCommand.Parameters.Add("@LastName", OleDbType.VarChar).Value = agentLastNametextBox4.Text.ToString();
ad.InsertCommand.Parameters.Add("@Email", OleDbType.VarChar).Value = agentEmailtextBox3.Text.ToString();
ad.InsertCommand.Parameters.Add("@Supervisor", OleDbType.VarChar).Value = agentSupervisortextBox2.Text.ToString();
con.Open();
ad.InsertCommand.ExecuteNonQuery();
con.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
};
我收到錯誤的查詢值數量和目標字段不相同。 我確定這是數據庫發送變量和導致問題的AgentID的方式。 我是新來的訪問者,但這就是我的工作想要使用的。 期待一個堅實的答案。
我只是使用一個名為Agents的簡單訪問數據庫
字段是
AgentID - auto number
FirstName - text
LastName - text
Email - text
Supervisor - text
當您編寫INSERT
語句時,它必須是這樣的:
INSERT INTO TableName VALUES (ValueList)
在這種情況下,必須為每個列提供值,並按它們添加到表中的順序提供它們,或者像這樣:
INSERT INTO TableName (ColumnList) VALUES (ValueList)
在這種情況下,您可以按任何順序指定列的子集。 你都沒做。 您已經這樣做:
INSERT INTO TableName VALUES (ColumnList)
這是沒有意義的。 您的SQL必須像這樣:
insert into Agents ([FirstName],[LastName],[Email],[Supervisor]) values (@FirstName,@LastName,@Email,@Supervisor)
請注意,這些值現在與您添加到命令中的參數匹配。
像這樣更改您的查詢
ad.InsertCommand = new OleDbCommand("insert into Agents values (@FirstName,@LastName,@Email,@Supervisor)", con);
要么
ad.InsertCommand = new OleDbCommand("insert into Agents (FirstName,LastName,Email,Supervisor) values (@FirstName,@LastName,@Email,@Supervisor)", con);
OleDb基於索引,並且不使用命名參數。
更改如下:
ad.InsertCommand = new OleDbCommand("insert into Agents (FirstName, LastName, Email, Supervisor) values (?, ?, ?, ?)", con);
ad.InsertCommand.Parameters.AddWithValue("?", agentNametextBox1.Text);
ad.InsertCommand.Parameters.AddWithValue("?", agentLastNametextBox4.Text);
ad.InsertCommand.Parameters.AddWithValue("?", agentEmailtextBox3.Text);
ad.InsertCommand.Parameters.AddWithValue("?", agentSupervisortextBox2.Text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.