选择表格取决于文本框值

时间:2012-08-30 11:27:50

标签: sql vb.net listview select

我刚以编程方式创建了一个表。我把它命名为我的文本框值。

示例:

Create table " & Textbox1.text & " + ......

我想根据文本框值设置我的表名。

Select TaskNumber,Name,Age From '" & Textbox1.text & "' "

2 个答案:

答案 0 :(得分:0)

最佳做法是将文本框值放在变量中:

    Dim myTableName As String
    myTableName = TexBox1.text

    // SQL Connection
    Dim conStr As String = "Server=MyServer;Database=Mydatabase;Trusted_Connection = yes"
    Dim objCon As New SqlConnection(conStr)
    Dim obj As SqlCommand
    Dim strSQL as String
    obj = objConn.CreateCommand()

    // *************** Select statement *********
    strSQL = "SELECT TaskNumber, Name, Age FROM " & myTableName

    // **************** Create statement *********
    strSQL = "CREATE TABLE " & myTableName & "(" & _
    "Id int NOT NULL PRIMARY KEY IDENTITY, " & _
    "ColumnTest VARCHAR(30)) "

    // Execute the command
    obj.CommandText = strSQL
    obj.ExecuteNonQuery()

答案 1 :(得分:0)

试试这个:

Dim query AS String = "Select TaskNumber,Name,Age From " & Textbox1.Text.Trim().Replace("'","")

.Replace(“'”,“”)会阻止SQL注入攻击,因为TextBox文本中存在单引号。

我建议您在TextBox上使用 RegularExpressionValidator 来限制允许的字符。