'= '附近语法错误.在代码c#中

本文关键字:代码 语法 错误 | 更新日期: 2023-09-27 18:07:52

我正在开发一个c#窗体应用程序,它可以保存学生的姓名、课程、年级等信息。我的代码保存到sql数据库工作,但当涉及到检索信息,我得到这些错误的语法不正确的'='附近。我认为错误是在检索代码。请帮忙:)

检索代码:

try
{
    string sql = "SELECT studnum,course,f_name,l_name,color_image FROM table3 WHERE f_name=" + textBoxfname.Text + "";
    if (conn.State != ConnectionState.Open)
        conn.Open();
    command = new SqlCommand(sql, conn);
    SqlDataReader reader = command.ExecuteReader();
    reader.Read();
    if (reader.HasRows)
    {
        labeloutputstudnum.Text = reader[0].ToString();
        labeloutputcourse.Text = reader[1].ToString();
        labeloutputfname.Text = reader[2].ToString();
        labeloutputlname.Text = reader[3].ToString();
        byte[] img = (byte[])(reader[4]);
        if (img == null)
            pictureBox3.Image = null;
        else
        {
            MemoryStream ms = new MemoryStream(img);
            pictureBox3.Image = Image.FromStream(ms);
        }
    }
    else
    {
        textBoxstudno.Text = "";
        textBoxcourse.Text = "";
        textBoxfname.Text = "";
        textBoxlname.Text = "";
        pictureBox3.Image = null;
        MessageBox.Show("does not exist");
    }
    conn.Close();
}
catch (Exception ex)
{
    conn.Close();
    MessageBox.Show(ex.Message);
}

'= '附近语法错误.在代码c#中

string sql = "SELECT studnum,course,f_name,l_name,color_image FROM table3 WHERE f_name=@Name";
command = new SqlCommand(sql, conn);
command.Parameters.Add(new SqlParameter("@Name", textBoxfname.Text));

我看到多个错误:

    最明显的是,总是在sql语句中使用参数。
  1. 总是使用using block来清理连接。
  2. 不要重用连接,这是不好的做法,因为sql server会自动(默认情况下,除非你完全关闭它)使用连接池。

    //不要重用连接,在需要的时候创建一个新的连接!使用(var conn = new SqlConnection(/使用web的连接/app .config/)){const string sql = "SELECT studentnum,course,f_name,l_name,color_image FROM table3 WHERE f_name = @name";

    command = new SqlCommand(sql, conn);
    command.Parameters.Add(new SqlParameter("@name", SqlDbType.VarChar) { Value = textBoxfname.Text});
    conn.Open();
    /* rest of code unchanged but do not call conn.Close(), the using block will do this for you
    

    }

所以回答你的问题,你的sql查询有不正确的语法。我会在sql字符串上断点,看看到底是什么错了。当你这样做的时候,它应该是显而易见的。

真正的问题是,你将你的应用程序暴露给SQL注入。让我们看一个基本的例子。

"SELECT * FROM table WHERE id ='" + userinput.Text + "'";

用户输入一些值,它被转储在那里用于查询。简单的对吧?

如果用户输入这个

会发生什么?
' OR 1=1; --

让我们看看添加了

后sql字符串变成了什么
SELECT * FROM table WHERE id = '' OR 1=1; -- '

现在,你的查询字符串说,select id OR where 1=1这意味着where为真,这意味着一切。

SQL注入是一个真正的威胁,阻止它的唯一方法是从一开始就实施对策。

请考虑参数化。这在c#中非常容易。

MSDN文章c#参数化

SQL中的字符串参数/字段必须使用单引号:

string sql = "SELECT studnum,course,f_name,l_name,color_image FROM table3 WHERE f_name='" + textBoxfname.Text + "'";
但是使用参数会更好(更安全):
string sql = "SELECT studnum,course,f_name,l_name,color_image FROM table3 WHERE f_name=@name";
if (conn.State != ConnectionState.Open)
    conn.Open();
var command = new SqlCommand(sql, conn);
command.Parameters.Add("@name", SqlDbType.NVarChar).Value = textBoxfname.Text;