更新数据库中的数据

时间:2014-04-09 16:21:09

标签: c# oledbcommand

我在尝试更新此数据时遇到问题,但始终提供错误消息......

private void btnEnterReturn_Click(object sender, EventArgs e)
{
        OleDbConnection connect = new OleDbConnection();
        connect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=MovieLibrary.accdb";
        connect.Open();
        addnew = "UPDATE tblLoan set MovieID='" + this.txtMovieID + "', DateIssued='" + this.txtDateIssued.Text + "', DateReturned='" + this.txtDateReturned.Text + "' WHERE MemberID='" + this.txtMemberID.Text + "';";

        com = new OleDbCommand(addnew, connect);

        com.ExecuteNonQuery();
        connect.Close();
        MessageBox.Show("Successfully returned..");

        //clear screen
        txtMemberID.Text = " ";
        txtMovieID.Text = " ";
        txtDateIssued.Text = " ";
        txtDateReturned.Text = " ";
}

1 个答案:

答案 0 :(得分:1)

您的错误是字符串连接。你总是得到糟糕的结果 (特别是当您尝试将日期和数字作为字符串或整个文本框控件而不是其Text属性传递时)。

而是使用格式良好的参数化查询

string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=MovieLibrary.accdb";
using(OleDbConnection connect = new OleDbConnection(conString))
{
     connect.Open();
     string addnew = @"UPDATE tblLoan set MovieID=?, DateIssued=?, DateReturned=?,
                       WHERE MemberID=?";
     using(OleDbCommand com = new OleDbCommand(addnew, connect))
     {
         com.Parameters.AddWithValue("@p1", Convert.ToInt32(this.txtMovieID.Text)
         com.Parameters.AddWithValue("@p2", Convert.ToDateTime(this.txtDateIssued.Text)
         com.Parameters.AddWithValue("@p3", Convert.ToDateTime(this.txtDateReturned.Text )
         com.Parameters.AddWithValue("@p4", Convert.ToInt32(this.txtMemberID.Text )
         com.ExecuteNonQuery();
         MessageBox.Show("Successfully returned..");
     }
}

在原始代码中,您尝试将txtMovieID作为MovieID字段的值传递,但是,从其名称我认为这是一个TextBox,因此您需要添加属性Text。

此外,我还假设您的txtDateIssued和txtDateReturned文本框包含日期时间值,相应的数据库字段需要日期时间。两个ID字段也是一样的。