我正在尝试使用文本框将值添加到我的数据库中。
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
string MemberID = txtMember.Text;
string FirstName = txtFirstName.Text;
string LastName = txtLastName.Text;
string Phone = txtTelephone.Text;
string Email = txtEmail.Text;
sql = " INSERT INTO A_Member ( MemberID, LastName, FirstName, Phone, Email) VALUES ( @Member, @LastName, @FirstName, @Phone, @Email);";
dbCmd = new OleDbCommand(sql, dbConn);
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
当我尝试使用添加按钮时,它表示“没有给出一个或多个参数的值。
这是我的.cs或.mdb文件中的内容吗?或者我可以改变代码的这一部分吗?
答案 0 :(得分:2)
您已在SQL代码中正确使用了参数,但尚未将这些参数添加到命令中,例如
dbCmd.Parameters.AddWithValue("@LastName", lastNameTextBox.Text);
您必须为SQL代码中显示的每个占位符添加一个参数。
答案 1 :(得分:1)
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
string memberID = txtMember.Text.Trim();
string firstName = txtFirstName.Text.Trim();
string lastName = txtLastName.Text.Trim();
string phone = txtTelephone.Text.Trim();
string email = txtEmail.Text.Trim();
sql = "INSERT INTO A_Member ( MemberID, LastName, FirstName, Phone, Email) VALUES ( @Member, @LastName, @FirstName, @Phone, @Email);";
dbCmd = new OleDbCommand(sql, dbConn);
dbCmd.Parameters.Add("@MemberID",SqlDbType.Int32).Value = Convert.ToInt32(memberID);
dbCmd.Parameters.Add("@LastName",SqlDbType.Varchar,30).Value = lastName;
dbCmd.Parameters.Add("@FirstName",SqlDbType.Varchar,30).Value = firstName;
dbCmd.Parameters.Add("@Phone",SqlDbType.Int32).Value = Convert.ToInt32(phone);
dbCmd.Parameters.Add("@LastName",SqlDbType.Varchar,30).Value = email;
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}