C# asp.net: error - No value given for one or more required parameters
Here is the code for the database layer function:
public static dsPersonnel GetPersonnel(string Database, string strSearch)
{
dsPersonnel DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
//create the connection string
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
string query;
if (strSearch == "" || strSearch.Trim().Length == 0)
{
query = "SELECT * from tblPersonnel";
}
else
{
query = "SELECT * FROM tblPersonnel WHERE LastName = " + strSearch + "";
}
//create the adapter with query
sqlDA = new OleDbDataAdapter(query, sqlConn);
//create the dataset
DS = new dsPersonnel();
//fill the data set
sqlDA.Fill(DS.tblPersonnel);
//return the dataset
return DS;
}
}
if the postback submits a blank string, i have it return all records. but when a real string is passed to the function, i get the error "no value given for one or more required parameters". for the line
sq开发者_高级运维lDA.Fill(DS.tblPersonnel);
In debug, I verified that the string is building correctly for both cases, but i get the error with the latter. I understand that I should be using parameterized queries, but this is the step in the learning process in class that I am on. One problem at a time :). Any suggestions on what the issue here is?
query =
"SELECT * FROM tblPersonnel WHERE LastName = '" +
strSearch +
"'";
Add quotes around the search criteria
You have to enclose strings in single quotes in SQL.
query = "SELECT * FROM tblPersonnel WHERE LastName = '" + strSearch + "'";
Try
query = "SELECT * FROM tblPersonnel WHERE LastName = '" + strSearch + "'";
or better
query = string.Format("SELECT * FROM tblPersonnel WHERE LastName = '{0}'", strSearch);
Doesn't look like you're quoting the parameter you're passing in to your query.
Instead of
query = "SELECT * FROM tblPersonnel WHERE LastName = " + strSearch + "";
try
query = "SELECT * FROM tblPersonnel WHERE LastName = '" + strSearch.Replace("'", "''") + "'";
Notice the extra single quotes, and also the Replace() statement which correctly escapes single quotes contained in your filter (e.g. apostrophes)
Must reiterate that your sample code does contain multiple problems and security vulnerabilities.
精彩评论