我正在开展一个创建注册系统的学校项目。我选择的数据库方法是使用 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 似乎是正确的版本。
任何人都可以阐明吗?
欣赏它,
Jamie
您的变量名称缺少单引号。将代码更改为以下内容以修复 SQL:
string degsql = "SELECT ModName FROM Module Where Degree = '" + Degree + "'";
或者这看起来稍微好一点:
string degsql = string.Format(
"SELECT ModName FROM Module Where Degree = '{0}'",
Degree);
但是,您不应该这样做,因为它会让您遭受 SQL 注入攻击。阅读这个问题以了解这意味着什么:参数化查询如何帮助防止 SQL 注入? https://stackoverflow.com/questions/5468425/how-do-parameterized-queries-help-against-sql-injection
下面是一些正确执行此操作并避免那些令人讨厌的安全问题的代码:
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";
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)