更新:谢谢大家,代码不是问题,但对于SQL注入的信息是有用的,我的问题是,我用我的数据库的较旧版本,并没有相应的产品ID,因此它是不是使用的第一款产品它可以找到。 现在感觉非常愚蠢的,但感谢您的建议。
目前,我有以下代码:
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();
我目前遇到的问题是,虽然在文本框中显示的按钮,点击该信息,显示的信息是数据库中的数据只在第一行,不对应于textbox3在SQL语句中的行
试试这个。 避免构建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帕特尔:THX的评论,你是完全正确的
其结果将是下面的SQL
SELECT * FROM Product WHERE ProductID=''; DROP TABLE Product; SELECT ''
这将允许恶意用户破坏你的数据库。
为了防止这种情况,你应该用准备好的发言的工作就像中号帕特尔在他的回答提出
你有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();
}
文章来源: How to display specific database entries into a textbox on a WinForm application