Sean Long
Sean Long

Reputation: 2301

Converting string to SQLCommand

I'm creating an app that has a text box where users can input a command to be run against a SQL Server instance. I've imported the System.Data.SqlClient object, and here's the code I have so far:

 Dim preSQLcmd As String = Me.txtPreSQL.Text
 Databasefn.preTestSQL(preSQLcmd)

Databasefn.preTestSQL looks like this:

Sub preTestSQL(cmd As SqlCommand)
    con = New SqlConnection("Data Source=" & utilnamespace.sqlSvr & ";Database=" & utilnamespace.testDbName & ";integrated security=SSPI;")
    cmd.Connection.Open()
    cmd.ExecuteNonQuery()
    cmd.Connection.Close()
End Sub

What am I missing here?

Upvotes: 1

Views: 712

Answers (1)

Steve
Steve

Reputation: 216243

Change your preTestSql to receive the string with the sql command text and then build the SqlCommand inside the procedure

Sub preTestSQL(cmdText As String)
    using con = New SqlConnection("Data Source=" & utilnamespace.sqlSvr & ";Database=" & utilnamespace.testDbName & ";integrated security=SSPI;")
    using cmd = new SqlCommand(cmdText, con)
         con.Connection.Open()
         cmd.ExecuteNonQuery()
    End Using
    End Using
End Sub

Said that I should ask. Are you sure that this is wise?.

A malicious user could easily destroy your whole database with a functionality like that.

Examples:

 UPDATE PayRoll SET WeekWage = 1000  -- (no where condition??)
 DELETE FROM Employee 

Upvotes: 3

Related Questions