如何用c#插入访问数据库

本文关键字:访问 数据库 插入 何用 | 更新日期: 2023-09-27 18:14:46

我正在尝试使用c#从winform添加数据到我的访问数据库。

我一直得到关于我的INSERT INTO语句的语法错误,无法看到我错在哪里。

请有人检查我的代码并告诉我哪里出错了。

private void btnLog_Click(object sender, EventArgs e)
{
    txtStatus.Text = "Open";
    conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:''Users''mwool''Desktop''Uni''3rd Year''SEM 1''AP''Assignment''Staff.accdb";
    string sql = "INSERT INTO Fault (faultType, Status, TechId, StaffId, Zone, Description) VALUES ('" + txtFaultType.Text + "', '" + txtStatus.Text + "', " + txtTechId.Text + "' , '" + txtStaffId.Text + "' , '" + txtZone.Text + "' , '" + txtDescription.Text + "')";
    OleDbCommand add = new OleDbCommand();
    add.CommandText = sql;
    add.Connection = conn;
    add.Connection.Open();
    add.ExecuteNonQuery();
    conn.Close();
}

如何用c#插入访问数据库

您在txtTechId.Text之前漏了一个单引号。但是,您应该始终使用参数化查询来避免SQL注入。

string sql = "INSERT INTO Fault (faultType, Status, TechId, StaffId, Zone, Description) VALUES (@a,@b,@c,@d,@e,@f)";
add.Parameters.AddWithValue("@a", txtFaultType.Text);
add.Parameters.AddWithValue("@b", txtStatus.Text);
add.Parameters.AddWithValue("@c", txtTechId.Text);
add.Parameters.AddWithValue("@d", txtStaffId.Text);
add.Parameters.AddWithValue("@e", txtZone.Text);
add.Parameters.AddWithValue("@f", txtDescription.Text);
  • 始终使用参数化查询。这可以防止简单的错误,如忘记'与字符串,但更重要的是防止sql注入攻击。

  • 始终将数据库连接,命令和任何其他一次性对象包装在using块中。

用using语句和参数化输入重构你的代码。

using (OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:''Users''mwool''Desktop''Uni''3rd Year''SEM 1''AP''Assignment''Staff.accdb"))
using (OleDbCommand cmd = new OleDbCommand())
{
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = string sql = "INSERT INTO Fault (faultType, Status, TechId, StaffId, Zone, [Description]) VALUES (?, ?, ?, ?, ?, ?)";
    cmd.Parameters.Add(new OleDbParameter("@faultType", OleDbType.VarChar)).Value = txtFaultType.Text;
    cmd.Parameters.Add(new OleDbParameter("@Status", OleDbType.VarChar)).Value = txtStatus.Text;
    // this parameter is an example of passing an int instead of a string. Alwaysuse the correct types!
    cmd.Parameters.Add(new OleDbParameter("@TechId", OleDbType.Int)).Value = int.Parse(txtTechId.Text);
    cmd.Parameters.Add(new OleDbParameter("@StaffId", OleDbType.VarChar)).Value = txtStaffId.Text;
    cmd.Parameters.Add(new OleDbParameter("@Zone", OleDbType.VarChar)).Value = txtZone.Text;
    cmd.Parameters.Add(new OleDbParameter("@Description", OleDbType.VarChar)).Value = txtDescription.Text;
    con.Open();
    cmd.ExecuteNonQuery();
}

OleDbCommand不支持命名参数,请参见OleDbCommand。参数

评论

当CommandType设置为Text时,OLE DB . net Provider不支持将参数传递给SQL语句或OleDbCommand调用的存储过程的命名参数。在这种情况下,必须使用问号占位符。


还要注意:

  • OleConnection和OleDbCommand被包裹在using块中,因此即使发生异常,它们也会被处理/清理。
  • 参数现在使用,而不是硬编码字符串值
  • 参数使用正确的数据类型

可能不允许使用Description,因为它是一个保留字(见链接)。在这种情况下,用[]包围它。