Create New Table on SQL Server with another table's schema - vb.net

I have a procedure in VB.net that when ran, determines if a table exists or not. If it doesn't exist I want to create a table on SQL Server with the same schema as a local FoxPro table. Is this something that can be done?
Here is what I have so far. Right now it just grabs the Schema from a Visual Foxpro table and displays it. Not sure where to go from here. Any ideas?
Private Sub dwprm01()
Try
Dim tableName As String = "dwprm01"
Dim tableExists As Boolean = False
Dim foxConn As New OleDbConnection("Provider=vfpoledb.1;Data Source=Z:\update_dwprm01\" & tableName & ".DBF;Collating Sequence=general;")
sConn.Open()
Dim restrictions(3) As String
restrictions(2) = tableName
Dim dbTbl As DataTable = sConn.GetSchema("Tables", restrictions)
Console.WriteLine("Checking if " & tableName & " exists")
If dbTbl.Rows.Count = 0 Then
'Table does not exist
tableExists = False
Console.WriteLine(tableName & " does not exist")
Console.WriteLine()
Console.WriteLine("Creating " & tableName)
Dim fSQL = "SELECT * FROM " & tableName
Dim cmd As New OleDbCommand(fSQL, foxConn)
foxConn.Open()
Dim myReader As OleDbDataReader = cmd.ExecuteReader()
Dim schema As DataTable = myReader.GetSchemaTable()
For Each row As DataRow In schema.Rows
For Each col As DataColumn In schema.Columns
Console.WriteLine(col.ColumnName & " = " & row(col).ToString())
Next
Next
myReader.Close()
foxConn.Close()
Else
'Table exists
tableExists = True
Console.WriteLine(tableName & " exists")
End If
dbTbl.Dispose()
sConn.Close()
sConn.Dispose()
Catch ex As Exception
Console.WriteLine(ex.ToString())
End Try
End Sub

Since you've already verified the new table does note exist, you just want to execute a query like this:
SELECT TOP 0 * INTO NewTable FROM OriginalTable
That will create a new table with no rows whose structure matches your original.

I was able to finally figure this out. Here is what I had to do. The commented block will show you different rows in the tables schema. The Case statement is yet to be finished either, but you can add onto this as you run into more datatypes needing to be converted.
Imports System.Data.OleDb
Module prm01_up
Dim sConn As New OleDbConnection("Provider=SQLNCLI10;Server=;Database=;Uid=;Pwd=;")
Sub Main()
Dim foxTables() As String = {"dwprm01", "lkpbrnch", "add_me", "empmastr"}
For Each tableName As String In foxTables
seekAndCreate(tableName)
Next
Console.WriteLine()
Console.WriteLine("Press any key to continue...")
Console.ReadKey()
End Sub
Private Sub seekAndCreate(ByRef tableName As String)
Try
Dim tableExists As Boolean = False
Dim foxConn As New OleDbConnection("Provider=vfpoledb.1;Data Source=Z:\update_dwprm01\" & tableName & ".DBF;Collating Sequence=general;")
sConn.Open()
Dim restrictions(3) As String
restrictions(2) = tableName
Dim dbTbl As DataTable = sConn.GetSchema("Tables", restrictions)
Console.WriteLine("Checking if " & tableName & " exists")
If dbTbl.Rows.Count = 0 Then
'Table does not exist
tableExists = False
Console.WriteLine(tableName & " does not exist")
Console.WriteLine()
Console.WriteLine("Creating " & tableName)
Dim foxDs As New DataSet
Dim fSQL As String = "USE " & tableName
Dim fCmd As New OleDbCommand(fSQL, foxConn)
foxConn.Open()
Dim objDR As OleDbDataReader
objDR = fCmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim schemaTable = objDR.GetSchemaTable()
Dim colName As String = String.Empty
Dim colSize As String = String.Empty
Dim colDataType As String = String.Empty
Dim newDataType As String = String.Empty
Dim allColumns As String = String.Empty
Dim colPrecision As String = String.Empty
Dim colScale As String = String.Empty
Dim createTable As New OleDbCommand
'For Each x As DataRow In schemaTable.Rows
' For Each y As DataColumn In schemaTable.Columns
' Console.WriteLine(y.ColumnName)
' Next
' Console.WriteLine()
'Next
For Each myField As DataRow In schemaTable.Rows
colName = myField(0).ToString
colSize = myField(2).ToString
colDataType = myField(5).ToString
colPrecision = myField(3).ToString
colScale = myField(4).ToString
Select Case colDataType
Case "System.String"
newDataType = "varchar" & "(" & colSize & "), "
Case "System.Decimal"
newDataType = "numeric(" & colPrecision & ", " & colScale & "), "
Case "System.DateTime"
newDataType = "datetime, "
Case "System.Int32"
newDataType = "int,"
Case Else
newDataType = colDataType.ToString()
End Select
allColumns += "[" & colName & "]" & " " & newDataType
Next
Console.WriteLine(allColumns.Substring(0, allColumns.Length - 2))
createTable.Connection = sConn
createTable.CommandType = CommandType.Text
createTable.CommandText = "CREATE TABLE " & tableName & " (" & allColumns & ")"
createTable.ExecuteNonQuery()
foxConn.Close()
Else
'Table exists
tableExists = True
Console.WriteLine(tableName & " exists")
Console.WriteLine()
End If
foxConn.Dispose()
dbTbl.Dispose()
sConn.Close()
Catch ex As Exception
Console.WriteLine(ex.ToString())
End Try
End Sub
End Module

Related

SSIS Create and Attaching file to the email

I've 2 sqlreaders and both should loop through it and second sqlreader data should create a table and inserting into the excel sheet.
Lets say
I've sqlreader and sqlreader1
sqlreader has some data which is required to get sqlreader1
I'm able to get sqlreader1 data as I expected
but once I loaded data to datatable, I'm loosing sqlreader1 and not able to see any info in sqlreader1
If SqlDataReader.HasRows Then
Do While SqlDataReader.Read()
Dim ExcelFileName As String = Dts.Variables("User::FolderPath").Value.ToString() + "Accrual_Input_Summary_Q" + SqlDataReader.Item("Accrual_Quarter").ToString() + " FY-" + SqlDataReader.Item("Accrual_FY").ToString() + ".xlsx"
'Dim recipientName As String = SqlDataReader.Item("recipient_name").ToString()
'Dim recipientEmail As String = SqlDataReader.Item("Recipient_Email").ToString()
Try
If System.IO.File.Exists(ExcelFileName) = True Then
System.IO.File.Delete(ExcelFileName)
End If
Dim SqlCmd1 As New SqlCommand("[POT].[PROC_POT_Accrual_Reminder_Summary]", SqlCon)
SqlCmd1.CommandType = CommandType.StoredProcedure
SqlCmd1.CommandTimeout = 0
SqlCmd1.Parameters.AddWithValue("#Qtype", "Accrual_Summary")
SqlCmd1.Parameters.AddWithValue("#Accrual_Created_By_Email", SqlDataReader.Item("Recipient_Email").ToString())
Dim SqlDataReader1 As SqlDataReader = SqlCmd1.ExecuteReader()
' connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" &
'"Data Source=" & ExcelFileName &
'";Extended Properties=Excel 12.0 Xml;HDR=YES;"
If SqlDataReader1.HasRows Then
While SqlDataReader1.Read()
Dim connectionString As String
Dim excelConnection As OleDbConnection
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & ExcelFileName & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=YES;"""
excelConnection = New OleDbConnection(connectionString)
Dim Excel_OLE_Cmd As OleDbCommand = New OleDbCommand()
Dim recipientName As String = SqlDataReader1.Item("Created_By_Name").ToString()
Dim recipientEmail As String = SqlDataReader1.Item("CostCenterAnalyst").ToString()
Dim costCenterOwner As String = SqlDataReader1.Item("CostCenterOwner").ToString()
Dim TableColumns As String = ""
Dim dtCustomers As New DataTable("sqlDataTable")
**dtCustomers.Load(SqlDataReader1)**
For Each column As DataColumn In dtCustomers.Columns
TableColumns += column.ToString() & "],["
Next
TableColumns = ("[" & TableColumns.Replace(",", " Text,").TrimEnd(","c))
TableColumns = TableColumns.Remove(TableColumns.Length - 2)
excelConnection.ConnectionString = connectionString
excelConnection.Open()
Excel_OLE_Cmd.Connection = excelConnection
Excel_OLE_Cmd.CommandText = "Create table " & "Sheet1" & " (" & TableColumns & ")"
Excel_OLE_Cmd.ExecuteNonQuery()
Dim sqlCommandInsert As String = ""
Dim sqlCommandValue As String = ""
For Each dataColumn As DataColumn In dtCustomers.Columns
sqlCommandValue += dataColumn.ToString() & "],["
Next
sqlCommandValue = "[" & sqlCommandValue.TrimEnd(","c)
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2)
sqlCommandInsert = "INSERT into " & "Sheet1" & "(" & sqlCommandValue & ") VALUES("
Dim columnCount As Integer = dtCustomers.Columns.Count
For Each row As DataRow In dtCustomers.Rows
Dim columnvalues As String = ""
For i As Integer = 0 To columnCount - 1
Dim index As Integer = dtCustomers.Rows.IndexOf(row)
columnvalues += "'" & dtCustomers.Rows(index).ItemArray(i).ToString() & "',"
Next
columnvalues = columnvalues.TrimEnd(","c)
Dim command As String = sqlCommandInsert & columnvalues & ")"
Excel_OLE_Cmd.CommandText = command
Excel_OLE_Cmd.ExecuteNonQuery()
Next
excelConnection.Close()
StrMailBody_Inner = " Hello Cost Center Analyst (" & recipientName & "), <br/><br/> PFA accrual inputs for the current quarter. Please review & take appropriate action click <a href='http://podashboarddev/' target='_blank'>here</a>.<br/><br/>"
StrMailBody_Inner = StrMailBody_Inner + " <u>Note</u><br/>"
StrMailBody_Inner = StrMailBody_Inner + " <ol>"
StrMailBody_Inner = StrMailBody_Inner + " <li>The accrual inputs provided doesn't interface with SAP. You will still need to post the necessary accrual JV.</li>"
StrMailBody_Inner = StrMailBody_Inner + " <li>CCA can leverage the tool for accrual tracking.</li>"
StrMailBody_Inner = StrMailBody_Inner + " </ol>"
Using myMessage As New MailMessage(Dts.Variables("email_from").Value, recipientEmail)
Dim copy As MailAddress = New MailAddress(costCenterOwner)
myMessage.CC.Add(copy)
myMessage.IsBodyHtml = True
myMessage.Subject = Dts.Variables("email_subject").Value
myMessage.Body = StrMailBody.ToString().Replace("$$$$Mail_Body$$$$", StrMailBody_Inner)
myMessage.Priority = System.Net.Mail.MailPriority.High
myMessage.Attachments.Add(New Attachment(ExcelFileName))
mySmtpClient = New SmtpClient("mailserver.amat.com")
mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials
'mySmtpClient.Send(myMessage)
Dim str_SQL As String
str_SQL = "INSERT INTO [POT].[tbl_POT_Open_PO_Accrual_Reminder_History] ([Recipient_Email], [Reminder_Type]) VALUES ('" + SqlDataReader.Item("recipient_email").ToString() + "', 'Accrual_Summary');"
Dim SqlCmdHist As New SqlCommand(str_SQL, SqlCon)
SqlCmdHist.CommandType = CommandType.Text
SqlCmdHist.CommandTimeout = 0
SqlCmdHist.ExecuteNonQuery()
SqlCmdHist.Dispose()
End Using
End While
SqlDataReader1.Close()
End If
Once I load data to Datatable using this
dtCustomers.Load(SqlDataReader1)
before load data:
after load data:
I'm missing the sqlreader1 and i'm unable to loop through it.
it is giving Invalid attempt to call Read when reader is closed.
Note: I've enabled MultipleActiveResultSets
can we do any other things that we can do to resolve this issue

Select last record added/updated in dgv

How to select the last record which is added or updated in datagridview
This is how i add
Insert into table (Name, AddDate) values ('" & Name & "', '" & Date.Now & "')"
After adding the record i refresh dgv
("Select * from table")
Form1.DGV.DataSource = SQLDataset1.Tables(0)
And this is how i update record
("Update table Set Name='" & txtT.Text & "' , DateEdit='" & Date.Now & "' Where Town= '" & txtT.Text & "'")
Edit :
Public Sub addIt(Name As String)
Try
Dim addStr As String = "Insert into tableName (Name, AddDate) values ('" & Name & "', '" & Date.Now & "')"
sqlcon.Open()
SqlCom = New SqlCommand(addStr, sqlcon)
SqlCom.ExecuteNonQuery()
sqlcon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
'Buton click event
If Len(town) >= 3 Then
sql.addIt(town)
Msgbox("Added")
sql.resetDGV()
End If
Public Sub resetDGV()
sqlquery("Select * from tableName")
Form1.dgv.DataSource = SQLDataset.Tables(0)
End Sub
There are easier ways outside in the www. But this is the shortest so....
Public Sub addIt(Name As String) as int
Dim insertedID as int = -1
Try
Dim addStr As String = "Insert into tableName (Name, AddDate) OUTPUT INSERTED.ID values ('" & Name & "', '" & Date.Now & "')"
sqlcon.Open()
SqlCom = New SqlCommand(addStr, sqlcon)
returnValue = Convert.ToInt32(SqlCom.ExecuteScalar())
sqlcon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
return insertedID
End Sub
If Len(town) >= 3 Then
Dim insertedID as int = sql.addIt(town)
If insertedID = -1 Then return
Msgbox("Added")
sql.resetDGV()
'Select
SelectLastInsertedRow(insertedID)
End If
Public Sub resetDGV()
sqlquery("Select * from tableName")
Form1.dgv.DataSource = SQLDataset.Tables(0)
End Sub
Private Sub SelectLastInsertedRow(id as int)
For Each row as DataGridViewRow in dgv.Rows
'Check if row belongs to the ID
if(row == id) Then
'Select
row.Select = true
End if
End For
End Sub
This code is not tested. But it should work :P

How to save the result of a SQL query into a variable in VBA?

I want to execute a select statement and put the result of it (which is only 1 record with 1 value) in a variable.
This is in VBA code in access.
Private Sub Child_Click()
Dim Childnummer As Integer
Dim childnaam As String
Childnummer = Me.Keuzelijst21.Value
DoCmd.Close
DoCmd.OpenForm "submenurubrieken", acNormal, , " rubrieknummer = " & Childnummer & ""
childnaam = rubrieknaamSQL(Childnummer)
Forms!submenurubrieken.Tv_rubrieknaam.Value = childnaam
End Sub
Public Function rubrieknaamSQL(Child As Integer)
Dim rst As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT rubrieknaam FROM dbo_tbl_rubriek where rubrieknummer = " & Child & ""
Set rst = CurrentDb.OpenRecordset(strSQL)
End Function
Simply have your Function return the value from the Recordset:
Public Function rubrieknaamSQL(Child As Integer)
Dim rst As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT rubrieknaam FROM dbo_tbl_rubriek where rubrieknummer = " & Child & ""
Set rst = CurrentDb.OpenRecordset(strSQL)
' new code:
rubrieknaamSQL = rst!rubrieknaam
rst.Close
Set rst = Nothing
End Function
You can do this in pretty much one line by using the "DLookup" Function
rubrieknaam = Nz(DLookup("rubrieknaam ", "dbo_tbl_rubriek ", rubrieknummer & " =[Child]"), 0)
where Child is the ID of the record you are looking for.

Read a text file which contains SQL code to create tables in a database

I need code to read a .txt file which is in my project bin\debug directory that contains SQL code to create tables in a large number it size of 936kb
This following code only I'm using...
By using this it gives result like table created but it is not reading the file... there is nothing in the database
Public Function readTextFile(ByVal fileName As String) As String
Dim strContent As String()
Dim x As String = ""
Try
'fileName = "CSYSS802.txt"
If Not System.IO.File.Exists(fileName) Then
'o Until EOF()
strContent = System.IO.File.ReadAllLines(fileName)
For Each Str As String In strContent
x = x + Str
Next
readTextFile = x
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
readTextFile = x
End Function
Public Sub createTable(ByVal vdbs As String, ByVal file As String)
username = frmlogin.txtusername.Text
password = frmlogin.txtusername.Text
vsvr = vServer
vdb = Trim$(vdbs)
strCon1 = "Server=" & vsvr & ";Database=" & vdb & ";uid=" & username & ";pwd=" & password & ";"
sqlCon1 = New SqlClient.SqlConnection(strCon1)
sqlCon1.Open()
Dim arr() As String
arr = Split(readTextFile(file), "GO")
Dim i As String
For Each i In arr
If i <> "" Then
Dim cmd2 As New SqlClient.SqlCommand("" & i & "")
cmd2.CommandType = CommandType.Text
cmd2.ExecuteNonQuery()
End If
Next
End Sub
In the readTextFile function, it will only attempt to read the text from the text file if the file DOESN'T exist. If the text file exists then the function returns an empty string and if the text file doesn't exist, the function will throw a file not found exception.
Replace:
If Not System.IO.File.Exists(fileName) Then
with:
If System.IO.File.Exists(fileName) = True Then
You might also want to include an Else clause in case the file doesn't exist as it won't throw an error since you have handled it correctly.
If System.IO.File.Exists(fileName) = True Then
strContent = System.IO.File.ReadAllLines(fileName)
For Each Str As String In strContent
x &= Str
Next
Return x
Else
MessageBox.Show("The file '" & fileName & "' does not exist.")
Return ""
End If
My Self I had Found The solution..I attache the Following Code...It now Creating All tables Properly..
Make sure that each Sql Commands in your Text File ends with go.. because i used "GO" Keyword to split the text...
Public Sub createTable(ByVal vdbs As String, ByVal file As String)
username = frmlogin.txtusername.Text
password = frmlogin.txtusername.Text
vsvr = vServer
vdb = Trim$(vdbs)
strCon1 = "Server=" & vsvr & ";Database=" & vdb & ";uid=" & username & ";pwd=" & password & ";"
sqlCon1 = New SqlClient.SqlConnection(strCon1)
sqlCon1.Open()
Dim arr() As String
arr = Split(readTextFile(file), " GO ")
Dim i As String
For Each i In arr
If i <> "" Then
Dim cmd2 As New SqlClient.SqlCommand("" & i & "", sqlCon1)
cmd2.CommandType = CommandType.Text
cmd2.ExecuteNonQuery()
End If
Next
End Sub
Public Function readTextFile(ByVal file As String) As String
Dim fso As New System.Object
Dim ts As Scripting.TextStream
Dim sLine As String
fso = CreateObject("Scripting.FileSystemObject")
ts = fso.openTextFile(file)
Do Until ts.AtEndOfStream
sLine = sLine & " " & ts.ReadLine
Loop
ts.Close()
fso = Nothing
readTextFile = sLine
End Function

Excel export without Interop

I'm trying to accomplish export to Excel from a VB.NET (Windows Forms) application.
Unfortunately, I can't use Office Interops because the application should work on every machine - even if there is no Excel installed.
I found the following sample on the Net:
Public Sub ExportDatasetToExcel(ByVal ds As DataSet, Optional ByVal strHeader As String = "Save As")
'Proudly copied from:
'http://www.daniweb.com/software-development/vbnet/threads/368400/write-into-excel-using-oledb-connection#post1583200
Dim fileSave As New SaveFileDialog()
fileSave.Filter = "Excel 97-2003 Workbook (*.xls)|*.xls"
fileSave.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
fileSave.Title = strHeader
fileSave.ShowDialog()
Dim xlsFilePath As String = fileSave.FileName
If xlsFilePath = "" Then
Exit Sub
End If
System.IO.File.Copy(storagePath & "\" & "empty.xls", xlsFilePath)
Cursor.Current = Cursors.WaitCursor
Dim conn As New OleDb.OleDbConnection(String.Format("provider=Microsoft.Jet.OLEDB.4.0; Data Source='{0}';" & "Extended Properties='Excel 8.0;HDR=YES;'", xlsFilePath))
conn.Open()
Dim strTableQ(ds.Tables.Count) As String
Dim i As Integer = 0
'making table query
For i = 0 To ds.Tables.Count - 1
strTableQ(i) = "CREATE TABLE [" & ds.Tables(i).TableName & "]("
Dim j As Integer = 0
For j = 0 To ds.Tables(i).Columns.Count - 1
Dim dCol As DataColumn
dCol = ds.Tables(i).Columns(j)
strTableQ(i) &= " [" & dCol.ColumnName & "] varchar(255) , "
Next
strTableQ(i) = strTableQ(i).Substring(0, strTableQ(i).Length - 2)
strTableQ(i) &= ")"
Dim cmd As New OleDb.OleDbCommand(strTableQ(i), conn)
cmd.ExecuteNonQuery()
Next
'making insert query
Dim strInsertQ(ds.Tables.Count - 1) As String
For i = 0 To ds.Tables.Count - 1
strInsertQ(i) = "Insert Into " & ds.Tables(i).TableName & " Values ("
For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
strInsertQ(i) &= "#" & ds.Tables(i).Columns(k).ColumnName & " , "
Next
strInsertQ(i) = strInsertQ(i).Substring(0, strInsertQ(i).Length - 2)
strInsertQ(i) &= ")"
Next
'Now inserting data
For i = 0 To ds.Tables.Count - 1
For j As Integer = 0 To ds.Tables(i).Rows.Count - 1
Dim cmd As New OleDb.OleDbCommand(strInsertQ(i), conn)
For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
cmd.Parameters.AddWithValue("#" & ds.Tables(i).Columns(k).ColumnName.ToString(), ds.Tables(i).Rows(j)(k).ToString())
Next
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
Next
Next
conn.Close()
conn.Dispose()
Cursor.Current = Cursors.Default
End Sub
This code works and exports my dataset to an .xls file.
The problem: I can't open this file while my program is running. It seems my program is still having a handle on this file. I can see it whenever I use the Sysinternals Process Explorer. If I close my program, I can open this file without any problems.
I think I have to destroy some object or just close the file. Please could anyone help a noob to accomplish it?
I don't know if this is the problem, it could. You do not Dispose the OleDbCommand objects. It's possible that it maintains a reference to the file. Try this:
Public Sub ExportDatasetToExcel(ByVal ds As DataSet, Optional ByVal strHeader As String = "Save As")
'Proudly copied from:
'http://www.daniweb.com/software-development/vbnet/threads/368400/write-into-excel-using-oledb-connection#post1583200
Using fileSave As New SaveFileDialog()
fileSave.Filter = "Excel 97-2003 Workbook (*.xls)|*.xls"
fileSave.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
fileSave.Title = strHeader
If fileSave.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim xlsFilePath As String = fileSave.FileName
If xlsFilePath = "" Then Exit Sub
System.IO.File.Copy(storagePath & "\" & "empty.xls", xlsFilePath)
Cursor.Current = Cursors.WaitCursor
Using conn As New OleDb.OleDbConnection(String.Format("provider=Microsoft.Jet.OLEDB.4.0; Data Source='{0}';" & "Extended Properties='Excel 8.0;HDR=YES;'", xlsFilePath))
conn.Open()
Dim strTableQ(ds.Tables.Count) As String
Dim i As Integer = 0
'making table query
For i = 0 To ds.Tables.Count - 1
strTableQ(i) = "CREATE TABLE [" & ds.Tables(i).TableName & "]("
Dim j As Integer = 0
For j = 0 To ds.Tables(i).Columns.Count - 1
Dim dCol As DataColumn
dCol = ds.Tables(i).Columns(j)
strTableQ(i) &= " [" & dCol.ColumnName & "] varchar(255) , "
Next
strTableQ(i) = strTableQ(i).Substring(0, strTableQ(i).Length - 2)
strTableQ(i) &= ")"
Using cmd As New OleDb.OleDbCommand(strTableQ(i), conn)
cmd.ExecuteNonQuery()
End Using
Next
'making insert query
Dim strInsertQ(ds.Tables.Count - 1) As String
For i = 0 To ds.Tables.Count - 1
strInsertQ(i) = "Insert Into " & ds.Tables(i).TableName & " Values ("
For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
strInsertQ(i) &= "#" & ds.Tables(i).Columns(k).ColumnName & " , "
Next
strInsertQ(i) = strInsertQ(i).Substring(0, strInsertQ(i).Length - 2)
strInsertQ(i) &= ")"
Next
'Now inserting data
For i = 0 To ds.Tables.Count - 1
For j As Integer = 0 To ds.Tables(i).Rows.Count - 1
Using cmd As New OleDb.OleDbCommand(strInsertQ(i), conn)
For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
cmd.Parameters.AddWithValue("#" & ds.Tables(i).Columns(k).ColumnName.ToString(), ds.Tables(i).Rows(j)(k).ToString())
Next
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
End Using
Next
Next
conn.Close()
Cursor.Current = Cursors.Default
End Using
End If
End Using
End Sub
Also note that a form that you display with ShowDialog() method must be disposed too.