admin

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

sql

我正在一个学校项目中创建注册系统。我选择的数据库方式是使用T-SQL,因为这已经为我所熟悉。

我正在使用以下代码查询数据库

    public void button3_Click(object sender, EventArgs e)
    {
        string StudentID = (textBox1.Text);
        string queryDOB = "SELECT DOB,LastName,Degree FROM Student Where StudentID = " + StudentID;

        SqlConnection con = new SqlConnection(Properties.Settings.Default.SRSConnectionString);
        con.Open();

        SqlCommand DOB = new SqlCommand(queryDOB, con);

        SqlDataReader stidreader = DOB.ExecuteReader();

        if (stidreader.Read())
        {
            textBox2.Text = stidreader["DOB"].ToString();
            textBox3.Text = stidreader["LastName"].ToString();
            textBox5.Text = stidreader["Degree"].ToString();
        }
        else
        {
            MessageBox.Show("Your ID is not recognised. Please try again.");
            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
            textBox5.Clear();
        }

        con.Close();
    }

    private void textBox5_TextChanged(object sender, EventArgs e)
    {
        string Degree = textBox5.Text;
        string degsql = "SELECT ModName FROM Module Where Degree = " + Degree;
        SqlConnection con = new SqlConnection(Properties.Settings.Default.SRSConnectionString);
        DataSet dsm = new DataSet();
        SqlDataAdapter connect = new SqlDataAdapter(degsql, con);

        con.Open();

        connect.Fill(dsm);
        this.listBox2.DataSource = dsm.Tables[0];
        this.listBox2.DisplayMember = "ModName";
}

单击按钮的第一部分效果很好,但是当我在下一个事件(文本框更改)中运行查询时,查询返回一条错误消息,指出已找到无效的列。好吧,找到的列是它应该用于查询的变量,而不是非常混乱的列本身。

我知道MARS可能存在问题,但DB似乎是正确的版本。

谁能阐明任何想法?


阅读 165

收藏
2021-07-01

共1个答案

admin

您缺少变量名周围的单引号。将您的代码更改为此以修复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";
2021-07-01