Skip to main content
 首页 » 编程设计

c#之在表名称为文本框文本的位置插入查询

2024年02月05日12artech

我在将数据插入表的 button1 单击事件中遇到问题,表名由 textbox1 中的任何文本确定

应该是这样的意思:

tablename = textbox1.text; 
 
sql = "INSERT INTO tablename ([itemserial], [itemname], [itemcount],[itemimage]) VALUES (@itemserial, @itemname, @itemcount, @itemimage)"; 

请您参考如下方法:

让包含表格名称的文本框具有挑战性,因为您在处理此值时应格外小心。您应该对此文本框值实现某种检查。一个可能的解决方案是检查您的数据库模式是否确实存在您的用户键入的表。

您没有告诉我们您使用的是哪个数据库系统,所以我将展示一个使用 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 更改为 ComboBox,并将 ComboBoxStyle 设置为 DropDownList(以阻止键入),并使用上面 GetSchema 调用返回的名称填充 ComboBox....