我在button1点击事件中遇到问题,该事件将数据插入表中,表名由textbox1中的任何文本确定
应该是这样的意思:
tablename = textbox1.text;
sql = "INSERT INTO tablename ([itemserial], [itemname], [itemcount],[itemimage]) VALUES (@itemserial, @itemname, @itemcount, @itemimage)";
答案 0 :(得分:2)
tablename = textbox1.text;
sql = string.Format("INSERT INTO {0} ([itemserial],[itemname],[itemcount],[itemimage])VALUES(@itemserial,@itemname,@itemcount,@itemimage)", tablename);
虽然我强烈建议不要这样做,因为它允许人们在文本框中输入他们想要的内容。类似的东西:
罗伯特; DROP TABLE学生; -
这里有更详细的讨论: How does the SQL injection from the "Bobby Tables" XKCD comic work?
答案 1 :(得分:2)
拥有包含表名称的文本框具有挑战性,因为您应该在处理此值时特别小心。您应该对此文本框值实施某种检查。如果用户键入的表确实存在,则可能的解决方案是检查数据库架构。
您没有告诉我们您使用的是哪个数据库系统,因此我将使用Sql Server
显示一个示例string tableName = textbox1.text;
using(SqlConnection cnn = new SqlConnection(... connectionstring...))
{
cnn.Open();
DataTable dt = cnn.GetSchema("TABLES");
DataRow[] rows = dt.Select("TABLE_NAME = '" + tableName + "'");
if(rows.Length > 0)
{
// Now you are sure to have a valid table in your textbox
// and could use the input value without risking an Sql Injection
string sql = "INSERT INTO [" + tableName + "] ([itemserial]," +
"[itemname],[itemcount],[itemimage]) " +
"VALUES(@itemserial,@itemname,@itemcount,@itemimage)";
.... the remainder of your code that use the query above....
}
else
MessageBox.Show("Please enter a valid name for your table");
扩展此方法,您可以将TextBox更改为ComboBoxStyle设置为DropDownList(以阻止键入)的ComboBox,并使用上面的GetSchema调用返回的名称填充ComboBox ....
答案 2 :(得分:0)
像这样更改您的查询
sql = "INSERT INTO "+tablename+" ([itemserial],[itemname],[itemcount],[itemimage]) VALUES (@itemserial,@itemname,@itemcount,@itemimage)";