string sqlCommand = "SELECT * " +
"FROM tblMatches " +
"WHERE matchPlayerNick ='" + comboBoxPlayer.Text + "' " +
"ORDER BY matchName ";
但上面的查询很容易受到sql injection
. 如果您使用 参数化这些值,则可以防止这种情况发生Command Object and Parameters
。
试试这个代码片段:
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()
}
}
}
为了正确编码
using
用于 propr 对象处理的use语句
- 使用
try-catch
块来正确处理对象