我是 C# 的新手,只学了几个星期。我正在编写一个带有 Windows 窗体的应用程序,后面是 Access 数据库。我希望将用户插入的详细信息添加到访问数据库中。我已经浏览了其他论坛(包括在 stackoverflow 上)以达到这一点,但我一直在运行时抛出一个错误,指出“没有为命令对象设置命令文本”(我突出显示了它出现在下面的行)我不明白,也无法摆脱。任何帮助将非常感激。谢谢K
private void btnOkay_Click(object sender, EventArgs e)
{
string connectionString =
"provider=Microsoft.ACE.Oledb.12.0;" +
"data source=C:\\Users\\Documents\\StudentRegistrationDatabase.accdb";
OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
string strSql = @"INSERT INTO StudentDetails ([Forename],[Surname],[CourseName],[DOB],)" +
"VALUES('"+txtFirstName.Text +"','" +txtLastName.Text +"','" +txtCourseName.Text +"','"+ txtDOB.Text +"')";
myOleDbConnection.Open();
OleDbCommand cmd = new OleDbCommand(strSql, myOleDbConnection);
cmd.Parameters.AddWithValue("@Forename", txtFirstName);
cmd.Parameters.AddWithValue("@Surname", txtLastName);
cmd.Parameters.AddWithValue("@CourseName", txtCourseName);
cmd.Parameters.AddWithValue("@DOB", txtDOB);
**myOleDbCommand.ExecuteNonQuery();** }
编辑:谢谢大家的回复。当我第一次开始编写这段代码时,我使用了以下代码行:
' {
string connectionString =
"provider=Microsoft.ACE.Oledb.12.0;" +
"data source=C:\\Users\\Botterill\\Documents\\StudentRegistrationDatabase.accdb";
OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
myOleDbConnection.Open();
myOleDbCommand.CommandText = "INSERT INTO StudentDetails ([Forename],[Surname],[CourseName],[DOB],)" +
"VALUES('" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtCourseName.Text + "','" + txtDOB.Text + "')";'
**myOleDbCommand.ExecuteNonQuery();**
但是,在粗体行中,我收到一个运行时错误,说“INSERT INTO 语句中存在语法错误”。我认为这将在我发布的第一个问题中所做的更改中得到纠正。任何帮助将不胜感激。谢谢凯特