简体   繁体   中英

OleDbCommand, No value given

With an Access table (Customers) and two fields (CustomerID, CustomerName):

string queryString = "INSERT INTO Customers (CustomerID, CompanyName)  VALUES (qqq, xyz)";
OleDbCommand command = new OleDbCommand(queryString, connection);
command.ExecuteNonQuery();

results in an error:

No value given for one or more required parameters

Both fields have a text Data Type

You should pass your values to the database engine using a parameterized query

string queryString = "INSERT INTO Customers (CustomerID, CompanyName)  VALUES (?,?)";
OleDbCommand command = new OleDbCommand(queryString, connection);
command.Parameters.AddWithValue("@p1", valueForCustomerIDFIeld)
command.Parameters.AddWithValue("@p2", valueForComapnyNameFIeld)
command.ExecuteNonQuery();

Actually I don't know what the qqq and xyz are. But embedding them inside the sql string cause them to be considered as parameter placeholders, thus the engine asks for two parameters.

I strongly suspect since you used qqq and xyz without single quotes, OleDbCommand see them as a parameter. That's why it expects some parameter values for both.

Because if they were strings, they would be used with single quotes like;

INSERT INTO Customers (CustomerID, CompanyName)  VALUES ('qqq', 'xyz')

If they are some variables, and want to add them to your command, you should always use parameterized queries to prevent SQL Injection attacks.

using(OleDbConnection connection = new OleDbConnection(conString))
using(OleDbCommand command = _connection.CreateCommand())
{
    command.CommandText = "INSERT INTO Customers(CustomerID, CompanyName) VALUES(?, ?)";
    command.Parameters.Add("@p1", OleDbType.VarChar).Value = qqq;
    command.Parameters.Add("@p2", OleDbType.VarChar).Value = xyz;
    connection.Open();
    command.ExecuteNonQuery();
}

And CustomerID is a very bad name for a character column because as a general ID part used for numerical values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM