Tool that will let you import data from SQL Server and Access to MySQL
Introduction
I needed to import data from MS SQL Server to MySQL. I first tried to use MySQL Workbench but ran into some problem. So I wrote
a tool to copy table schema and data to MySQL. You can download it here.
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 1/12
20/02/2019 MySQL Data Importer - CodeProject
Background
I have tested the tool against MS SQL Server and Access databases. Not all data types are supported. You can modify the
application to support other data types and databases (like Oracle).
Required Components
In case you do not have MySQL ODBC driver or Microsoft Access OLEDB provider, you can download them here:
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 2/12
20/02/2019 MySQL Data Importer - CodeProject
txtConnect.Text = sConnectionString
SetTableCombo()
End Sub
EditConnectionString function uses DataLinks ActiveX object to generate the connection string based on user input. The
ease of working with COM objects is the primary reason I chose VB.NET for this app.
cn.ConnectionString = sConnectionString
oDataLinks.hWnd = Me.Handle
cn.Open()
Return cn.ConnectionString
Catch ex As Exception
MsgBox(ex.Message)
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 3/12
20/02/2019 MySQL Data Importer - CodeProject
Return ""
End Try
End Function
Once you enter MySQL server information and click Test, the connection information will be saved into registry and
GetMySqlConnectionString() will create the MySQL connection string. The user will see Success message box or an Error
message box.
Try
Dim cnOdbc As OdbcConnection = New OdbcConnection(GetMySqlConnectionString())
cnOdbc.Open()
cnOdbc.Close()
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
MsgBox("Success")
End Sub
When the form is opened, this sub will retrieve the connection string from the registry. It will also call SetTableCombo() to
populate the list of available tables.
txtServer.Text = oAppRegistry.GetRegistryValue("Server")
txtDatabase.Text = oAppRegistry.GetRegistryValue("Database")
txtUser.Text = oAppRegistry.GetRegistryValue("User")
txtPassword.Text = oAppRegistry.GetRegistryValue("Password")
End Sub
SetTableCombo() to populate the list of available tables. It uses GetOleDbSchemaTable() function to get list of tables
from an OLEDB connection.
Sub SetTableCombo()
cboTable.Items.Clear()
oTable = cnOleDb.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, _
New Object() {Nothing, Nothing, Nothing, "TABLE"})
cnOleDb.Close()
Catch ex As Exception
MsgBox(Err.Description)
Exit Sub
End Try
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 4/12
20/02/2019 MySQL Data Importer - CodeProject
End Sub
When you click on the "Copy tables" button, this sub will check if SetTableCombo() populated the table list and will also
check if user selected a table(s) to export. Next, it will loop through the list of selected tables and call ExportTable sub for
each table.
If cboTable.Items.Count = 0 Then
MsgBox("Please connect to the source database.")
Exit Sub
End If
If cboTable.CheckedItems.Count = 0 Then
MsgBox("Please select tables to copy.")
Exit Sub
End If
txtLog.Clear()
cnOdbc.Close()
cn.Close()
End If
End Sub
Try
Dim oMySqlCmd As New OdbcCommand("SELECT Count(*) FROM " & sTableName, cnOdbc)
iMySqlRecCount = Integer.Parse(oMySqlCmd.ExecuteScalar().ToString())
bMySqlTableExists = True
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 5/12
20/02/2019 MySQL Data Importer - CodeProject
Catch ex As Exception
'Ignore - assume table dos not exist
End Try
OpenConnections(cn, cnOdbc)
Dim sSql1 As String = "DELETE FROM " & sTableName
Dim oCmd1 As New OdbcCommand(sSql1, cnOdbc)
Try
oCmd1.ExecuteNonQuery()
Catch ex As Exception
Log(ex.Message & vbTab & "SQL: " & sSql1)
End Try
End If
If chkCreateTable.Checked Then
If bMySqlTableExists Then
Log("Drop table: " & sTableName)
Try
oCmdDrop.ExecuteNonQuery()
bMySqlTableExists = False
Catch ex As Exception
Log("Could not drop table: " & sTableName & ", " & ex.Message & vbTab)
End Try
End If
If sConnectionString.IndexOf(".ACE.OLEDB") = -1 _
OrElse sConnectionString.IndexOf(".JET.OLEDB") = -1 Then
sSql1 = GetColumnsTableAccess(sTableName, cn)
Else
sSql1 = GetColumnsTableSqlServer(sTableName, cn)
End If
Try
oCmd1.ExecuteNonQuery()
bMySqlTableExists = True
Catch ex As Exception
Log(ex.Message & vbTab & "SQL: " & sSql1)
End Try
End If
'Copy Data
ProgressBar1.Maximum = iCount
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 6/12
20/02/2019 MySQL Data Importer - CodeProject
lbCount.Visible = True
Log("Copying " & iCount & " rows from table: " & sTableName)
'Get Header
Dim sHeader As String = ""
For i = 0 To oSchemaRows.Count - 1
Dim sColumn As String = oSchemaRows(i)("ColumnName")
If i <> 0 Then
sHeader += ", "
End If
sHeader += sColumn
Next
While dr.Read()
sRow = ""
For i = 0 To oSchemaRows.Count - 1
If sRow <> "" Then
sRow += ", "
End If
sRow += GetValueString(dr.GetValue(i))
Next
OpenConnections(cn, cnOdbc)
Dim sSql1 As String = "INSERT INTO " & sTableName _
& " (" & sHeader & ") VALUES (" & sRow & ")"
Dim oCmd1 As New OdbcCommand(sSql1, cnOdbc)
Try
oCmd1.ExecuteNonQuery()
Catch ex As Exception
Log(ex.Message & vbTab & "SQL: " & sSql1)
End Try
iRow += 1
ProgressBar1.Value = iRow
lbCount.Text = iRow.ToString()
lbCount.Refresh()
End While
dr.Close()
ProgressBar1.Value = 0
lbCount.Visible = False
lbCount.Text = ""
OpenConnections sub is called regularly just in case the database connection got closed.
End Sub
GetMySqlConnectionString function will create MySQL connection string based on user information.
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 7/12
20/02/2019 MySQL Data Importer - CodeProject
Case "System.Boolean"
If (obj = True) Then
Return "1"
Else
Return "0"
End If
Case "System.String"
Dim str As String = obj
Return "'" + str.Replace("'", "''") + "'"
Case "System.DateTime"
Return "STR_TO_DATE('" + obj.ToString() + "','%m/%d/%Y %r')"
Case "System.Drawing.Image"
Return "NULL"
Case "System.Drawing.Bitmap"
Return "NULL"
Case "System.Byte[]"
Return "0x" + GetHexString(obj)
Case Else
Return obj.ToString()
End Select
End Function
GetHexString function will encode binary data into hexadecimal string. This function is called by GetValueString.
Return sb.ToString()
End Function
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 8/12
20/02/2019 MySQL Data Importer - CodeProject
GetColumnsTableSqlServer function uses SQL Server INFORMATION_SCHEMA.COLUMNS systems view to create the
CREATE TABLE statement.
sb.Append("CREATE TABLE " & sTableName & " (" & vbCrLf)
Dim i As Integer = 0
While dr.Read
Dim sColumn As String = dr.GetValue(dr.GetOrdinal("COLUMN_NAME")).ToString()
Dim sDataType As String = dr.GetValue(dr.GetOrdinal("DATA_TYPE")).ToString()
Dim bAllowDBNull As Boolean = dr.GetString(dr.GetOrdinal("IS_NULLABLE")) = "YES"
Dim sColumnSize As String = dr.GetValue(dr.GetOrdinal_
("CHARACTER_MAXIMUM_LENGTH")).ToString()
If i > 0 Then
sb.Append(",")
sb.Append(vbCrLf)
End If
sb.Append(PadColumnName(sColumn))
sb.Append(" " & sDataType)
If bAllowDBNull Then
sb.Append(" NULL")
Else
sb.Append(" NOT NULL")
End If
i += 1
End While
sb.Append(")")
dr.Close()
If i = 0 Then
Return ""
Else
Return sb.ToString()
End If
End Function
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 9/12
20/02/2019 MySQL Data Importer - CodeProject
Dim sSql As String = "select * from " & PadColumnName(sTableName) & " where 0=1"
If i > 0 Then
sb.Append(",")
sb.Append(vbCrLf)
End If
sb.Append(PadColumnName(sColumn))
sb.Append(" " & PadAccessDataType(sDataType, sColumnSize))
If bAllowDBNull Then
sb.Append(" NULL")
Else
sb.Append(" NOT NULL")
End If
i += 1
Next
sb.Append(")")
dr.Close()
If i = 0 Then
Return ""
Else
Return sb.ToString()
End If
End Function
End Function
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 10/12
20/02/2019 MySQL Data Importer - CodeProject
Imports Microsoft.Win32
Catch ex As Exception
MsgBox("Update registry failed: " & ex.Message, , "DeleteBlankPages")
End Try
End Sub
Return sValue
End Function
End Class
History
4th May, 2016: Initial version
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 11/12
20/02/2019 MySQL Data Importer - CodeProject
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Igor is a business intelligence consultant working in Tampa, Florida. He has a BS in Finance from University of South Carolina and
Masters in Information Management System from University of South Florida. He also has following professional certifications:
MCSD, MCDBA, MCAD.
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile Article Copyright 2016 by Igor Krupitsky
Web05 | 2.8.190214.1 | Last Updated 20 Feb 2019 Everything else Copyright © CodeProject, 1999-2019
https://www.codeproject.com/Articles/1097407/MySQL-Data-Importer?display=Print 12/12