c#中没有给出一个或多个必需参数的值

本文关键字:参数 一个 | 更新日期: 2023-09-27 18:02:29

没有为mycommand.ExecuteNonQuery()的一个或多个必需参数给定值…我想知道是什么问题……有人能帮忙吗?谢谢=)

System.Data.OleDb.OleDbConnection cnregister;
    System.Data.OleDb.OleDbCommand cnUpreg;
    System.Data.OleDb.OleDbDataReader ReaderReg;
    private void cmdregister_Click(object sender, EventArgs e)
    {
        cnregister = new System.Data.OleDb.OleDbConnection();
        string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=|DataDirectory|Register.mdb";
        OleDbConnection myConnection = new OleDbConnection(connectionString);
        string InputId_reg;
        string InputPass_reg;
        InputId_reg = txtuserid_reg.Text;
        InputPass_reg = txtpass_reg.Text;
        myConnection.Open();

        OleDbCommand cnUpreg = new OleDbCommand("SELECT * FROM tblRegister", myConnection);
        ReaderReg = cnUpreg.ExecuteReader();     //reader open
        while (ReaderReg.Read())
        {
            if (InputId_reg == (ReaderReg["UserID"].ToString()) )
            {   //to check whether the UserID is same with the ID in the database
                // if yes, a message box will promt                 
                MessageBox.Show("The user had register");
                txtuserid_reg.Focus();
                txtuserid_reg.Clear ();
                ReaderReg.Close();
                myConnection.Close();
                break;
            }
            else
            {
                string query123 = "INSERT INTO [tblRegister] ([UserID], [Password], [UserName], [UserJob]) VALUES(add1, add2, add3, add4)";
                OleDbCommand mycommand = new OleDbCommand(query123, myConnection);
                mycommand.Parameters.AddWithValue("add1", txtuserid_reg.Text);
                mycommand.Parameters.AddWithValue("add2", txtpass_reg.Text);
                mycommand.ExecuteNonQuery();
                ReaderReg.Close();
                myConnection.Close();
                MessageBox.Show("Data save successfully!");
                break;

            }
        }
        MessageBox.Show("Break succesffully");
    }
}

c#中没有给出一个或多个必需参数的值

您在查询中要求4个参数,但只分配2个:

string query123 = "INSERT INTO [tblRegister] ([UserID], [Password], [UserName], [UserJob]) VALUES(add1, add2, add3, add4)";
OleDbCommand mycommand = new OleDbCommand(query123, myConnection);
mycommand.Parameters.AddWithValue("add1", txtuserid_reg.Text);
mycommand.Parameters.AddWithValue("add2", txtpass_reg.Text);
// Need UserName and UserJob to satisfy your insert query
mycommand.ExecuteNonQuery();
...

我不确定您的应用程序是如何设置的,但您需要添加如下内容:

mycommand.Parameters.AddWithValue("add3", txtusername_reg.Text);
mycommand.Parameters.AddWithValue("add4", txtuserjob_reg.Text);

或者把你的查询改成:

string query123 = "INSERT INTO [tblRegister] ([UserID], [Password]) VALUES(add1, add2)";

我猜这一行设置了4个"参数"的查询

string query123 = "INSERT INTO [tblRegister] ([UserID], [Password], [UserName], [UserJob]) VALUES(add1, add2, add3, add4)";

…然后在ExecuteNonQuery

之前只添加两个