Reputation: 31
I have written the following script (in c#):
string sqlCommand = "SELECT * " +
"FROM tblMatches " +
"WHERE matchPlayerNick =" + comboBoxPlayer.Text + " " +
"ORDER BY matchName ";
When I run my program, I get this: "data type mismatch in the criteria experssion". the datatype of matchPlayer is, of course, "text".
what's wrong with the script then?
thanks!
Upvotes: 0
Views: 107
Reputation: 263723
string sqlCommand = "SELECT * " +
"FROM tblMatches " +
"WHERE matchPlayerNick ='" + comboBoxPlayer.Text + "' " +
"ORDER BY matchName ";
but the query above is vulnerable with sql injection
. It can be prevented if you parameterized the values using Command Object and Parameters
.
Try this code snippet:
string content = comboBoxPlayer.Text;
string connStr = "connection string here";
string sqlCommand = @"SELECT *
FROM tblMatches
WHERE matchPlayerNick = @content
ORDER BY matchName";
using (SqlConnection conn = new SqlConnection(connStr))
{
using(SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = sqlStatement;
comm.CommandType = CommandType.Text;
comm.Parameters.AddWithValue("@content", content);
try
{
conn.Open();
// other codes here
}
catch(SqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}
For proper coding
using
statement for propr object disposaltry-catch
block to properly handle objectsUpvotes: 4
Reputation: 6692
You've forgotten the quotes. Using parameterized queries, it's a good practice.
Upvotes: 4