Selecting table depends on textbox value - sql

I just created a table programmatically. I named it as my Textbox value.
Example:
Create table " & Textbox1.text & " + ......
I want to set my table name according to my Textbox value.
Select TaskNumber,Name,Age From '" & Textbox1.text & "' "

The best pratice would be to put your textbox value in a variable:
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()

Try this:
Dim query AS String = "Select TaskNumber,Name,Age From " & Textbox1.Text.Trim().Replace("'","")
.Replace("'","") will prevent SQL-Injection attack due to the presence of single quotes in the TextBox text.
I will suggest you using RegularExpressionValidator on your TextBox to limit the allowed characters.

Related

Represent field in DB by variable

I have a project which is linked with a MDB file. I need to filter records of a table based on a condition, and both "field name" and the value or conditions should be passed to a Sub via variables. The select statement doesn't work. Did I miss something?
Dim Result() As DataRow
Dim strField As String = "asset_code"
Dim dblValue As Double = 3
Dim tblName as Datatable = AssetsDataSet.Assets
Result = tblName.Select(" '" & strField & "' = '" & dblValue& "' ")
I suspect that you need to loose the single quotes around the field name and as the data because it looks like it is numeric:
Result = tblName.Select(strField & " = " & cstr(dblValue) )
With string data you need to use a function:
Result = tblName.Select("textfield = " & cSQL(StringData) )
Function cSQL(psTextData As String) As String
' Replace any single quotes to be 2 single quotes
Return "'" + Replace(psTextData, "'", "''") + "'"
End Function

'if exist' SQL query in VBA with ADODB database connection

I need to uplad data from excel into a database, but I need to check first if there is data in the table for each upload so that I Update or Insert data.
To diferentiate Update or Insert, I'm usign a SQL IF EXIST command, which works okay in SQL. When I try this in Excel VBA I get an error message: "Command text was not set for the command object."
See code below
Dim strSQL As String
Dim Value As String
Dim Reference As String
Set RCconn = New ADODB.Connection
Set TuneCMD = New ADODB.Command
' Establish Recordset
Set Results = New ADODB.Recordset
'Establish a Connection
With RCconn
.Provider = "SQLOLEDB"
.ConnectionString = ConStr
End With
'Open the connection
RCconn.Open
'i Columns
For i = 5 To 10 '16
'j rows
For j = 6 To 60 '145
Value= Sheets("Value").Cells(j, i)
Reference= "W_F/P_" & Sheets("Reference").Cells(j, i)
stringTest = "IF EXISTS (SELECT * FROM UploadTable WHERE Ref = '" & Reference & "') "
stringTest = stringTest & "UPDATE Val "
stringTest = stringTest & "SET Val = '" & Value & "' "
stringTest = stringTest & "where Ref = '" & Reference & "' "
stringTest = stringTest & "Else "
stringTest = stringTest & "INSERT INTO UploadTable (Val , Ref ) "
stringTest = stringTest & "values ('" & Value & "', '" & Reference & "')"
RCconn.Execute strSQL
Next
Next
Set Results = Nothing
RCconn.Close
Set RCconn = Nothing
Is it the case that 'IF EXIST' can not be used in VBA? Is there a work around?
Thanks
ADODB.Connection.Execute sends a pass-through query to your database. It doesn't matter what SQL statement was in that string; if your database can understand it, it will be executed.
So inspect your SQL query again.
Try this:
Put a breakpoint on the line RCconn.Execute strSQL. When the debugger breaks there, inspect the value of strSQL. Copy it and execute in SQL Server Management Studio directly. If that doesn't work, correct your code that builds that string. If it works, then there is some problem with your ConnectionString. In that case, check that the userID and password you are using in the ConnectionString to connect has adequate privileges.

easiest way to add a SQL column through VB

What i want to do is first check if a certain column already exists in a table and if not add it. I want to implement this through visual basic. If somebody took a little time to comment and briefly explain each step i would greatly appreciate it.
There are two ways to determine if a column exists: either try to use it and catch the error if it doesn't exist, or read the metadata from the database see SQL Server: Extract Table Meta-Data (description, fields and their data types)
Once you know that you need to add the column you use the ALTER TABLE command to add the column to the table.
Here is vb.net script to check if column exist, if not, create it..
''' summary
''' Checks to see if a table exists in Database or not.
'''
''' Table name to check
''' Connection String to connect to
''' Works with Access or SQL
'''
Public Function DoesTableExist(ByVal tblName As String, ByVal cnnStr As String) As Boolean
' For Access Connection String,
' use "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
' accessFilePathAndName
' Open connection to the database
Dim dbConn As New OleDbConnection(cnnStr)
dbConn.Open()
' Specify restriction to get table definition schema
' For reference on GetSchema see:
' http://msdn2.microsoft.com/en-us/library/ms254934(VS.80).aspx
Dim restrictions(3) As String
restrictions(2) = tblName
Dim dbTbl As DataTable = dbConn.GetSchema("Tables", restrictions)
If dbTbl.Rows.Count = 0 Then
'Table does not exist
DoesTableExist = False
Else
'Table exists
DoesTableExist = True
End If
dbTbl.Dispose()
dbConn.Close()
dbConn.Dispose()
End Function
'''
''' Checks to see if a field exists in table or not.
'''
''' Table name to check in
''' Field name to check
''' Connection String to connect to
'''
'''
Public Function DoesFieldExist(ByVal tblName As String, _
ByVal fldName As String, _
ByVal cnnStr As String) As Boolean
' For Access Connection String,
' use "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
' accessFilePathAndName
' Open connection to the database
Dim dbConn As New OleDbConnection(cnnStr)
dbConn.Open()
Dim dbTbl As New DataTable
' Get the table definition loaded in a table adapter
Dim strSql As String = "Select TOP 1 * from " & tblName
Dim dbAdapater As New OleDbDataAdapter(strSql, dbConn)
dbAdapater.Fill(dbTbl)
' Get the index of the field name
Dim i As Integer = dbTbl.Columns.IndexOf(fldName)
If i = -1 Then
'Field is missing
DoesFieldExist = False
Else
'Field is there
DoesFieldExist = True
End If
dbTbl.Dispose()
dbConn.Close()
dbConn.Dispose()
End Function
Dim connString As String = "Data Source=NameOfMachine\InstanceofSQLServer;Initial Catalog=NameOfDataBase;Integrated Security=True"
Dim MyCol As String = "NameOfColumn"
Dim MyTable As String = "[NameOfTable]" ' or "[Name Of Table]" use brackets if table name contains spaces or other illegal Characters
Dim MySql As String = "IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS" & vbCrLf &
"WHERE TABLE_NAME = '" & MyTable & "' AND COLUMN_NAME = '" & MyCol & "')" & vbCrLf &
"BEGIN" & vbCrLf &
"ALTER TABLE [dbo]." & MyTable & " ADD" & vbCrLf & "[" & MyCol & "] INT NULL ;" & vbCrLf & "END"
Try
' MsgBox(MySql)- this msg box shows the Query so I can check for errors- Not required for code.
Dim dbConn = New SqlConnection(connString)' Note ConnString must be declared in the form class or within this Sub. Connstring is your connection string
Dim dbCmd = New SqlCommand(MySql, dbConn)
dbConn.Open()
dbCmd.ExecuteNonQuery()
'MessageBox.Show("Ready To Load Addendums")
dbConn.Close()
Catch ex As Exception
MsgBox("We've encountered an error;" & vbCrLf & ex.Message)
End Try

Preventing escaping apostrophes with parameter query not working

I am trying to prevent from having to escape apostrophes in my string variables by using a parameterized query with a SqlConnection, but it is not working. any help would be appreciated.
UPDATED: this is current code...
'Populate Connection Object
Dim oCnn As New SqlConnection(strConnection)
'Define our sql query
Dim sSQL As String = "INSERT INTO [" & foreignTable & "] (data_text) VALUES (#data_text) ; "
'Populate Command Object
Dim oCmd As New SqlCommand(sSQL, oCnn)
'Add up the parameter, associated it with its value
oCmd.Parameters.AddWithValue("#data_text", data_text)
'Opening Connection for our DB operation
oCnn.Open()
Try
Dim results As Integer = oCmd.ExecuteScalar
Catch ex As Exception
LabelImport.Text &= "<font color=red>ROOT Import ERROR: " & ex.ToString & ", From Database: " & dbName & ", Text String: " & data_text & "</font><br />"
Throw
End Try
oCnn.Close()
oCmd.Parameters.Clear()
Thanks for any help.
Yeah, that's not right.
It should look like this:
Dim sSQL As String = "INSERT INTO [" & foreignTable & "] (data_text) VALUES (#data_text);"
and for the parameter:
oCmd.Parameters.AddWithValue("#data_text", data_text)
Note: I don't "think" you can pass the table name as a parameter. You would have to have the table name in the string. See Parametise table name in .Net/SQL?
Also, change this:
Dim results As Integer = oCmd.ExecuteScalar
to
Dim results as Integer = oCmd.ExecuteNonQuery()
You can use table name only when creating query (I mean concatenating it from parts: "INSERT INTO " + foreignTable + " (data_text) VALUES..., AFAIK), not as query parameter. Check SqlParameterCollection.AddWithValue on MSDN for more information about SqlCommand parameters, there is very good example as well.
'Populate Connection Object
Dim oCnn As New SqlConnection(strConnection)
'Define our sql query
Dim sSQL As String = "INSERT INTO " & foreignTable & " (data_text) VALUES (#data_text);"
'Populate Command Object
Dim oCmd As New SqlCommand(sSQL, oCnn)
'Add up the parameter, associated it with its value
oCmd.Parameters.AddWithValue("#data_text", data_text)
'Opening Connection for our DB operation
oCnn.Open()
Edit:
+ changed to & because of C# as "native language".

How do I store the results of my select statement in a variable?

My code so far is this. The last line gives me a compile error: "expected end of statement".
Dim strSql As String
Dim groupId As String
strSql = "Select ID from RevenueGroup where description = '" & ListO.Value & "'"
groupId = CurrentProject.Connection.Execute strSql
You are looking at something kinda like this
Dim strSql As String
Dim groupId As String
strSql = "Select ID from RevenueGroup where description = '" & ListO.Value & "'"
Dim rec As Recordset
set rec= CurrentProject.Connection.Execute strSql
groupId = rec(0)
You need to set the results of the query to a recordset and then pull the first value from its results. Without all the defined variable, I cannot get this to fully compile but this should be a good template to start from.