如何在WinForm应用程序的文本框中显示特定的数据库条目

更新:谢谢大家,代码是不是问题,虽然关于SQL注入的信息是有用的,我的问题是,我使用的数据库的旧版本没有相应的产品ID,所以它是使用第一个产品它可以find。 感觉非常愚蠢,但感谢您的build议。

我目前有以下代码:

SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\v11.0 AttachDbFilename=C:\Users\h8005267\Desktop\Practical Project\Build\System4\System\StockControl.mdf;Integrated Security=True;Connect Timeout=30"); connection.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM Product WHERE ProductID='" + textBox3.Text + "'", connection); SqlDataReader re = cmd.ExecuteReader(); if (re.Read()) { textBox4.Text = re["ProductTitle"].ToString(); // only fills using first product in table textBox5.Text = re["ProductPublisherArtist"].ToString(); comboBox1.Text = re["ProductType"].ToString(); textBox6.Text = re["Price"].ToString(); } else { MessageBox.Show("Please enter a valid item barcode"); } re.Close(); connection.Close(); 

我目前遇到的问题是,尽pipe文本框显示button单击信息,显示的信息只是数据库中的第一行数据,而不是与sql语句中的textbox3对应的行

试试这个。 避免动态构建SQL语句。 您正在打开您的数据库到SQL注入的风险。 使用参数insead。

 using (var connection = new SqlConnection("connection string")) { connection.Open(); using (var cmd = new SqlCommand("SELECT * FROM Product WHERE ProductID=@MYVALUE", connection)) { cmd.Parameters.Add("@MYVALUE", SqlDbType.VarChar).Value = textBox3.Text; SqlDataReader re = cmd.ExecuteReader(); if (re.Read()) { textBox4.Text = re["ProductTitle"].ToString(); // only fills using first product in table textBox5.Text = re["ProductPublisherArtist"].ToString(); comboBox1.Text = re["ProductType"].ToString(); textBox6.Text = re["Price"].ToString(); } else { MessageBox.Show("Please enter a valid item barcode"); } } } 

在这一行上放置一个断点

 SqlDataReader re = cmd.ExecuteReader(); 

并在textBox3中输入以下内容

 '; DROP TABLE Product; SELECT ' 

'将被输入到您的文本框中。 现在执行你的方法,仔细阅读结果的SQL命令…欢迎来到SQL注入;)

@M Patel:thx您的评论,你是完全正确的

结果将是下面的SQL

 SELECT * FROM Product WHERE ProductID=''; DROP TABLE Product; SELECT '' 

这将允许恶意用户破坏你的数据库。

为了防止你应该像M帕特尔在他的回答中所建议的那样准备好陈述

你有SQL注入问题'" + textBox3.Text + "'"

而且你不必像这样命名你的控件,你必须使用一个有意义的名字

你可以使用这个代码

 using (SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\v11.0 AttachDbFilename=C:\Users\h8005267\Desktop\Practical Project\Build\System4\System\StockControl.mdf;Integrated Security=True;Connect Timeout=30")) { connection.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM Product WHERE ProductID=@ProductID", connection); cmd.Parameters.AddWithValue("@ProductID", textBox3.Text); SqlDataReader re = cmd.ExecuteReader(); if (re.Read()) { textBox4.Text = re.GetString(re.GetOrdinal("ProductTitle")); // only fills using first product in table textBox5.Text = re.GetString(re.GetOrdinal("ProductPublisherArtist")); comboBox1.Text = re.GetString(re.GetOrdinal("ProductType")); textBox6.Text = re.GetString(re.GetOrdinal("Price")); } else { MessageBox.Show("Please enter a valid item barcode"); } re.Close(); }