C#中的多个SQL查询返回变量作为列

C#中的多个SQL查询返回变量作为列,第1张

C#中的多个SQL查询返回变量作为列

您缺少变量名周围的单引号。将您的代码更改为此以修复SQL:

string degsql = "SELECt ModName FROM Module Where Degree = '" + Degree + "'";

或者看起来更好一点:

string degsql = string.Format(    "SELECt ModName FROM Module Where Degree = '{0}'",     Degree);

但是,您不应以这种方式这样做,因为它会使您遭受SQL注入攻击。

这是一些正确执行此代码并避免那些讨厌的安全性问题的代码:

private void textBox5_TextChanged(object sender, EventArgs e){    string Degree = textBox5.Text;    string degsql = "SELECt ModName FROM Module Where Degree = @Degree";    DataSet dsm = new DataSet();    using(var con = new SqlConnection(Properties.Settings.Default.SRSConnectionString))    {        SqlCommand cmd = new SqlCommand(degsql, con);        // use the appropriate SqlDbType:        var parameter = new SqlParameter("@Degree", SqlDbType.Varchar);        parameter.Value = Degree;        cmd.Parameters.Add(parameter);        SqlDataAdapter connect = new SqlDataAdapter(cmd);        connect.Fill(dsm);    }    this.listBox2.DataSource = dsm.Tables[0];    this.listBox2.DisplayMember = "ModName";


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5011111.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存