0

这里我向表中添加 5 个数据(注册),它包含 6 个六列,其中 ID 是主 KEY 标识。但是我遇到了一个例外,即“myCommand.ExecuteReader();”中的一个或多个必需参数没有值 在尝试插入其他数据列时。

public void SubmitClick(Object sender, EventArgs e )
{
    insertdata(FN.Text,LN.Text,DOB.Text,mailid.Text,username.Text);
}
public void insertdata(string fname, string sname, string dob ,string email ,string uname)
{

    //Connection string for the datbase
    string database = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\atchutharamkj\documents\visual studio 2010\Projects\WebApplication1\WebApplication1\App_Data\Database3.accdb;Persist Security Info=True";
    OleDbConnection myConn = new OleDbConnection(database);
    string queryStr = @"Insert into Registration Values (fname , sname, dob , email, uname)";
    OleDbCommand myCommand = new OleDbCommand(queryStr, myConn);
    myCommand.Connection.Open();
    myCommand.ExecuteReader();
    myCommand.Connection.Close();

}
4

1 回答 1

4

您的查询是错误的,这样您就不会向它传递任何东西。

使用这样的参数化查询:

public void SubmitClick(Object sender, EventArgs e )
{
    insertdata(FN.Text,LN.Text,DOB.Text,mailid.Text,username.Text);
}

public void insertdata(string fname, string sname, string dob ,string email ,string uname)
{
    string database = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\atchutharamkj\documents\visual studio 2010\Projects\WebApplication1\WebApplication1\App_Data\Database3.accdb;Persist Security Info=True";
    OleDbConnection myConn = new OleDbConnection(database);

    string queryStr = @"Insert into Registration(FirstName,LastName,DOB,[E-Mail],Username ) Values (?, ?, ?, ?, ?)";

    OleDbCommand myCommand = new OleDbCommand(queryStr, myConn);
    myCommand.Parameters.AddWithValue("@fname", fname);
    myCommand.Parameters.AddWithValue("@sname", sname);
    myCommand.Parameters.AddWithValue("@dob", dob);
    myCommand.Parameters.AddWithValue("@email", email);
    myCommand.Parameters.AddWithValue("@uname", uname);

    myCommand.Connection.Open();
    myCommand.ExecuteNonQuery();
    myCommand.Connection.Close();
}

有关将参数传递给 OleDB 的更多信息,请参阅MSDN

于 2013-10-23T07:41:54.133 回答