一个sql字符串错误(c#)

本文关键字:错误 sql 字符串 一个 | 更新日期: 2023-09-27 18:11:55

我写了下面的脚本(用c#):

string     sqlCommand = "SELECT   * " +
                 "FROM     tblMatches " +
                 "WHERE matchPlayerNick =" + comboBoxPlayer.Text + " " +
                 "ORDER BY matchName ";

当我运行程序时,我得到这个:"标准表达式中的数据类型不匹配"。matchPlayer的数据类型当然是"text".

那剧本怎么了?

谢谢!

一个sql字符串错误(c#)

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语句进行适当的对象处理
  • 使用try-catch块来正确处理对象

你忘了引号了。使用参数化查询是一种很好的做法。