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
Related
I'm trying to create columns in an existing access database. The database has already been created, it contains the empty table named "table1", but it does not contain any columns, now I want to add a column into it. But it produces some error.
Arguments are of the wrong type, are out of acceptable range, or are
in conflict with one another.
Imports ADOX
Imports ADOX.DataTypeEnum
Imports ADOX.KeyTypeEnum
Imports System.Data.OleDb
Imports System.Data.SqlClient
Dim database_location As String = Application.UserAppDataPath
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
insert_columns("DB3", "table1", "Key", adInteger, True, True)
End Sub
Function insert_columns(ByRef Database_file_name As String, ByRef table_name As String, ByRef column_name As String, ByRef data_type As ADOX.DataTypeEnum, Optional ByRef primary_key As Boolean = False, Optional ByRef auto_increment As Boolean = False)
Dim DB_file_name As String = "\" & Database_file_name & ".mdb"
Dim catDB As ADOX.Catalog
Dim tblNew As ADOX.Table
' Dim catstring As String
'Try
catDB = New ADOX.Catalog
' Open the catalog.
catDB.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & database_location & DB_file_name
tblNew = New ADOX.Table
' Create a new Table object.
With tblNew
.Name = table_name
.ParentCatalog = catDB
' Create fields and append them to the
' Columns collection of the new Table object.
With .Columns
.Append(column_name, data_type)
If auto_increment = True Then
.Item(column_name).Properties("AutoIncrement").Value = True
End If
If primary_key = True Then
tblNew.Keys.Append("PrimaryKey", KeyTypeEnum.adKeyPrimary, column_name)
End If
End With
End With
' Add the new Table to the Tables collection of the database.
catDB.Tables.Append(tblNew)
'clean up
catDB = Nothing
tblNew = Nothing
Return True
'Catch ex As Exception
' error_entry("Column creation error. Database name: " & DB_file_name & " Column Name: " & column_name & vbNewLine & ex.Message)
' Return False
'End Try
End Function
Argh, didn't read properly that you are using adox. I'll leave the answer just in case.
I used ACE but it should be the same:
Using cmd As New OleDb.OleDbCommand() 'Creates table and columns in it
cmd.Connection = <your connection>
cmd.CommandText = "CREATE TABLE [" & <table_name> & "]([<column_name>] <COLUMN TYPE>, ...repeat)" ' so it looks like "CREATE TABLE [NewTable]([Column1] TEXT, [Columnnnnz2] INTEGER)
cmd.ExecuteNonQuery()
End Using
If you want to add columns independently then Add columns to an Access (Jet) table from .NET
I need your help PLEASE!
I have a table: tblCustomer. (serial,Name,Email,Address)
I did the following:
insert-update-delete in dataset(that contains the table tblCustomer)
What I need to do, and I need your help in it, is:
insert-update-delete in dataview.
I tried to do the following:
Dim dv As New DataView(_DataSet.Tables(0))
' select deleted rows
dv.RowStateFilter = DataViewRowState.Deleted
For _irow As Long = 0 To dv.Table.Rows.Count - 1
' if serial is null, that means the row is new and deleted
' so no need to add it to database
If Not IsDBNull(dv!serial) Then
' delete row from database
Dim _SQL As String = "DELETE FROM tblCustomer WHERE Serial = " & dv!serial.ToString
' open the connection and execute the delete command
Dim strconnection As String = "Data Source=EASMAR-PC;Initial Catalog=Database Connection;Integrated Security=True;"
Dim _cn As SqlConnection = New SqlConnection(strconnection)
_cn.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "Delete from tblCustomer where serial= '" & txtSerial.Text & "'"
End If
Next
I am getting this error: Conversion from string "serial" to type 'Integer' is not valid.
On this line: If Not IsDBNull(dv!serial) Then
And the same error on: Dim _SQL As String = "DELETE FROM tblCustomer WHERE Serial = " & dv!serial.ToString
Can you help me PLEASE.
Thank you.
what type is serial? Integer I guess, from the error. Plus it seems you're passing the literal string value "serial" instead of a number.
Also, in your two DELETE statements you're passing it both WITH and WITHOUT ' '.
remove those ' '.
And what's that _SQL string variable? you're not using it.
Try:
If Not IsDBNull(dv!serial) Then
' open the connection and execute the delete command
Dim strconnection As String = "Data Source=EASMAR-PC;Initial Catalog=Database Connection;Integrated Security=True;"
Dim _cn As SqlConnection = New SqlConnection(strconnection)
_cn.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "Delete from tblCustomer where serial= " & txtSerial.Text
End If
What is the most efficient way to insert multiple records into an Access DB with VB.net?
I have a list of objects with multiple properties which are the values for an INSERT query and I want to know can I insert them all together instead of looping through the list of objects, building the query string and executing the queries one by one which is very slow.
Rough example of what I have:
For Each Val In ValueList
ValueString = Val.X.ToString & ", "
ValueString += Val.Y.ToString & ", "
ValueString += Val.Z.ToString
SQLValueList.Add(ValueString)
Next
Dim cmd As OleDb.OleDbCommand
Dim strConnection As String
Dim strSql As String = Nothing
strConnection = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\db.accdb;" & _
"User ID=Admin;Password=;"
For Each ValueString As String In SQLValueList
strSql = "INSERT INTO Results (FldX, FldY, FldZ)" &
"VALUES ( " & ValueString & ");"
cmd = New OleDb.OleDbCommand(strSql)
cmd.Connection = New OleDb.OleDbConnection(strConnection)
cmd.Connection.Open()
cmd.ExecuteNonQuery()
Next
I'm assuming there is a much better and more efficient way of doing this but I haven't been able to find it!
Yes a parameterized query
Imports System.Data.OleDb
.......
Dim strConnection As String
Dim strSql As String = Nothing
strConnection = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\db.accdb;" & _
"User ID=Admin;Password=;"
strSql = "INSERT INTO Results (FldX, FldY, FldZ) VALUES ( ?, ?, ?)"
using cn = new OleDbConnection(strConnection)
using cmd = new OleDbCommand(strSql, cn)
cn.Open()
' HERE all the parameters are added with a string dummy value. '
' This should be changed if one of the underlying field is of different type '
' For example, if FldX is of type integer your need to write '
' cmd.Parameters.AddWithValue("#p1", 0) and then in the loop code '
' '
' cmd.Parameters(0).Value = val.X or '
' cmd.Parameters(0).Value = Convert.ToInt32(val.X) if val.X is not an integer but convertible to... '
cmd.Parameters.AddWithValue("#p1", "")
cmd.Parameters.AddWithValue("#p2", "")
cmd.Parameters.AddWithValue("#p3", "")
For Each val In ValueList
cmd.Parameters(0).Value = val.X.ToString()
cmd.Parameters(1).Value = val.Y.ToString()
cmd.Parameters(2).Value = val.Z.ToString()
cmd.ExecuteNonQuery()
Next
End Using
End Using
This is just an example because it is not clear what kind of data is stored in your ValueList (strings, integers, doubles dates?), but I hope that the idea is clear. Create a command object with 3 parameters (one for each field to insert), add every parameter to the command collection with dummy values (in the example, every parameter contains a string value but you need to add the correct datatype for the underlying field type). At this point just loop one time on your values and execute the query.
Please, stay away to string concatenation to build an sql command, expecially when the string values to concatenate are typed by your user. You risk an Sql Injection attack
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.
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".