Creating MySQL Database tables using Visual Basic. Net

In this tutorial, I’m going to show you how to create a MySQL database tables dynamically in a simple way. To start in this lesson, we need to understand first the concept of creating a MySQL database table. The creation of table command requires the following: Name of the table, Names of fields and Definitions for each field. The generic syntax of creating a MySQL table is like as shown below:
  1. CREATE TABLE table_name (column_name column_type);
This time, let’s start building our application. First open Visual basic and create a new project and Name it as “tblcreator”. After creating a new project, we will then add objects to our form and these objects are the following: three labels, three buttons, two combobox, one textbox, one datagridview and a groupbox. Then arrange all objects looks like as shown below. Next, for datagridview1 we need to add 6 columns. And these are: Field, type, Length/Values, Null, Index and Auto. Here’s the settings for datagridview columns:
Selected Columns	Properties		Settings
Field			Header Text		Field
			DatapropertyName	n_field
			Name			n_field
			ColumnType		DataGridViewTextBoxColumn
type			Header Text		type
			DatapropertyName	n_type
			Name			n_type
			ColumnType		DataGridViewComboBoxColumn
			Items			INT
VARCHAR
TEXT
DATE
Lenght/Values		Header Text		Lenght/Values
			DatapropertyName	n_Lenght
			Name			n_Lenght
			ColumnType		DataGridViewTextBoxColumn
NULL			Header Text		Null
			DatapropertyName	n_null
			Name			n_null
			ColumnType		DataGridViewCheckBoxColumn
			Truevalue 		NOT NULL
			Falsevalue		NULL
Index			Header Text		Index
			DatapropertyName	n_index
			Name			n_index
			ColumnType		DataGridViewComboBoxColumn
Items			PRIMARY KEY
UNIQUE	
INDEX
FULLTEXT
Auto Increment		Header Text		Auto Increment
			DatapropertyName	n_ai
Truevalue		AUTO_INCREMENT
			Name			n_ai
			ColumnType		DataGridViewCheckBoxColumn
After we set the datagriview columns, here are few items need explanation: • Field Attribute NOT NULL is being used because we do not want this field to be NULL. So if user will try to create a record with NULL value, then MySQL will raise an error. • Field Attribute NOT NULL is being used because we do not want this field to be NULL. So if user will try to create a record with NULL value, then MySQL will raise an error. • Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next available number to the id field. • Keyword PRIMARY KEY is used to define a column as primary key. You can use multiple columns separated by comma to define a primary key. This time, lets add functionality to our application. To do this, double click the form and add the following code below public class.
  1. 'Represents an SQL statement or stored procedure to execute against a data source.
  2. Dim cmd As New MySqlCommand
  3. Dim da As New MySqlDataAdapter
  4. Public total As Integer
  5. Dim publictable As New DataTable
  6. 'declare conn as connection and it will now a new connection because
  7. 'it is equal to Getconnection Function
  8. Dim con As MySqlConnection = jokenconn()
  9.  
  10. Public Function jokenconn() As MySqlConnection
  11. Return New MySqlConnection("server=localhost;user id=root;password=;database=")
  12. End Function
Then, on the form1_load add the following code. This will populate the combobox with database name.
  1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  2. GroupBox1.Text = "Create new table on database "
  3. Dim sql As String = "SHOW DATABASES"
  4. Dim publictable As New DataTable
  5. Try
  6.  
  7. 'bind the connection and query
  8. With cmd
  9. .Connection = con
  10. .CommandText = sql
  11. End With
  12.  
  13. da.SelectCommand = cmd
  14. da.Fill(publictable)
  15.  
  16. With cbdb
  17. .DataSource = publictable
  18. .DisplayMember = "Database"
  19. .ValueMember = "Database"
  20. End With
  21.  
  22. da.Dispose()
  23.  
  24. Catch ex As Exception
  25. MsgBox(ex.Message)
  26.  
  27. End Try
  28. con.Clone()
  29.  
  30. End Sub
Next, we need to display all the MySQL Database tables on the combobox provided for table name based on the Database selected. To do this, double click the “use” button and add the following code:
  1. Private Sub btntest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btntest.Click
  2. GroupBox1.Text = "Create new table on database " & cbdb.Text
  3. Dim sql As String = "SHOW TABLES FROM " & cbdb.Text
  4. Dim publictable As New DataTable
  5. Try
  6.  
  7. 'bind the connection and query
  8. With cmd
  9. .Connection = con
  10. .CommandText = sql
  11. End With
  12.  
  13. da.SelectCommand = cmd
  14. da.Fill(publictable)
  15. ' publictable.Rows.Add("Please Select...")
  16. With cbtable
  17. .DataSource = publictable
  18. .DisplayMember = "Tables_in_" & cbdb.Text
  19. .ValueMember = "Tables_in_" & cbdb.Text
  20.  
  21. End With
  22. ' dtgrd.Columns(1).Visible = False
  23. da.Dispose()
  24.  
  25. Catch ex As Exception
  26. MsgBox(ex.Message)
  27.  
  28. End Try
  29. con.Clone()
  30.  
  31. End Sub
Then in order to enable the “create” button, we need to pass first to “Add” button. To do this, add the following code:
  1. txttblName.ReadOnly = False
  2. btnCreateTbl.Visible = True
  3. btnAddtbl.Visible = False
next, double click our “create” button and add the following code:
  1. Private Sub btnCreateTbl_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateTbl.Click
  2.  
  3. Dim field As String
  4. Dim type As String
  5. Dim nlenght As Integer
  6. Dim nNull As String
  7. Dim nIndex As String
  8. Dim nAI As String
  9. Dim alltxt As String
  10. Dim result As Integer
  11.  
  12. Dim tblAndDB As String = cbdb.Text & "." & txttblName.Text
  13. Dim TBLCREATE As String = "CREATE TABLE " & tblAndDB & " ( "
  14.  
  15. For i As Integer = 0 To Me.dtgStructNewTbl.Rows.Count - 2
  16.  
  17. ' field.Add(Me.dtgStructNewTbl.Rows(i).Cells("n_field").Value)
  18. field = Me.dtgStructNewTbl.Rows(i).Cells("n_field").Value
  19. type = Me.dtgStructNewTbl.Rows(i).Cells("n_type").Value
  20. nlenght = Me.dtgStructNewTbl.Rows(i).Cells("n_lenght").Value
  21. nNull = Me.dtgStructNewTbl.Rows(i).Cells("n_null").Value
  22. nIndex = Me.dtgStructNewTbl.Rows(i).Cells("n_index").Value
  23. nAI = Me.dtgStructNewTbl.Rows(i).Cells("n_ai").Value
  24.  
  25. alltxt += field & " " & type & "(" & nlenght & ")" & " " & nNull & " " & nIndex & " " & nAI & "," & vbNewLine
  26.  
  27. Next
  28. Try
  29. 'it removes all the newline and whitespaces
  30. alltxt = alltxt.Substring(0, alltxt.Length - Environment.NewLine.Length)
  31. Dim cleanText As String
  32. 'it removes the the last comma ","
  33. cleanText = alltxt.Remove(alltxt.Length - 1)
  34. Dim finalText As String
  35. 'combination of finalText with table name and Mysql ENGINE
  36. finalText = TBLCREATE & cleanText & ")ENGINE = MYISAM ;"
  37.  
  38. con.Open()
  39. With cmd
  40. .Connection = con
  41. .CommandText = finalText
  42. result = cmd.ExecuteNonQuery
  43. If result > 0 Then
  44. MsgBox("No Table has created!")
  45. Else
  46. MsgBox(txttblName.Text & " has created Successfully!")
  47. With Me
  48. .txttblName.ReadOnly = True
  49. .btnCreateTbl.Visible = False
  50. .btnAddtbl.Visible = True
  51. .dtgStructNewTbl.SendToBack()
  52. '.dtgStructNewTbl.Columns.Clear()
  53. End With
  54.  
  55.  
  56. End If
  57. End With
  58.  
  59.  
  60. Form1_Load(sender, e)
  61.  
  62. Catch ex As Exception
  63. MsgBox(ex.Message)
  64. End Try
  65. con.Close()
  66. End Sub
And here’s all the code use for this application.
  1. Imports MySql.Data.MySqlClient
  2. Public Class Form1
  3. 'Represents an SQL statement or stored procedure to execute against a data source.
  4. Dim cmd As New MySqlCommand
  5. Dim da As New MySqlDataAdapter
  6. Public total As Integer
  7. Dim publictable As New DataTable
  8. 'declare conn as connection and it will now a new connection because
  9. 'it is equal to Getconnection Function
  10. Dim con As MySqlConnection = jokenconn()
  11.  
  12. Public Function jokenconn() As MySqlConnection
  13. Return New MySqlConnection("server=localhost;user id=root;password=;database=")
  14. End Function
  15. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  16. GroupBox1.Text = "Create new table on database "
  17. Dim sql As String = "SHOW DATABASES"
  18. Dim publictable As New DataTable
  19. Try
  20.  
  21. 'bind the connection and query
  22. With cmd
  23. .Connection = con
  24. .CommandText = sql
  25. End With
  26.  
  27. da.SelectCommand = cmd
  28. da.Fill(publictable)
  29.  
  30. With cbdb
  31. .DataSource = publictable
  32. .DisplayMember = "Database"
  33. .ValueMember = "Database"
  34. End With
  35.  
  36. da.Dispose()
  37.  
  38. Catch ex As Exception
  39. MsgBox(ex.Message)
  40.  
  41. End Try
  42. con.Clone()
  43.  
  44. End Sub
  45.  
  46. Private Sub btntest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btntest.Click
  47. GroupBox1.Text = "Create new table on database " & cbdb.Text
  48. Dim sql As String = "SHOW TABLES FROM " & cbdb.Text
  49. Dim publictable As New DataTable
  50. Try
  51.  
  52. 'bind the connection and query
  53. With cmd
  54. .Connection = con
  55. .CommandText = sql
  56. End With
  57.  
  58. da.SelectCommand = cmd
  59. da.Fill(publictable)
  60. ' publictable.Rows.Add("Please Select...")
  61. With cbtable
  62. .DataSource = publictable
  63. .DisplayMember = "Tables_in_" & cbdb.Text
  64. .ValueMember = "Tables_in_" & cbdb.Text
  65.  
  66. End With
  67. ' dtgrd.Columns(1).Visible = False
  68. da.Dispose()
  69.  
  70. Catch ex As Exception
  71. MsgBox(ex.Message)
  72.  
  73. End Try
  74. con.Clone()
  75.  
  76. End Sub
  77.  
  78. Private Sub btnAddtbl_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddtbl.Click
  79. txttblName.ReadOnly = False
  80. btnCreateTbl.Visible = True
  81. btnAddtbl.Visible = False
  82. End Sub
  83.  
  84. Private Sub btnCreateTbl_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateTbl.Click
  85.  
  86. Dim field As String
  87. Dim type As String
  88. Dim nlenght As Integer
  89. Dim nNull As String
  90. Dim nIndex As String
  91. Dim nAI As String
  92. Dim alltxt As String
  93. Dim result As Integer
  94.  
  95. Dim tblAndDB As String = cbdb.Text & "." & txttblName.Text
  96. Dim TBLCREATE As String = "CREATE TABLE " & tblAndDB & " ( "
  97.  
  98. For i As Integer = 0 To Me.dtgStructNewTbl.Rows.Count - 2
  99.  
  100. ' field.Add(Me.dtgStructNewTbl.Rows(i).Cells("n_field").Value)
  101. field = Me.dtgStructNewTbl.Rows(i).Cells("n_field").Value
  102. type = Me.dtgStructNewTbl.Rows(i).Cells("n_type").Value
  103. nlenght = Me.dtgStructNewTbl.Rows(i).Cells("n_lenght").Value
  104. nNull = Me.dtgStructNewTbl.Rows(i).Cells("n_null").Value
  105. nIndex = Me.dtgStructNewTbl.Rows(i).Cells("n_index").Value
  106. nAI = Me.dtgStructNewTbl.Rows(i).Cells("n_ai").Value
  107.  
  108. alltxt += field & " " & type & "(" & nlenght & ")" & " " & nNull & " " & nIndex & " " & nAI & "," & vbNewLine
  109.  
  110. Next
  111. Try
  112. 'it removes all the newline and whitespaces
  113. alltxt = alltxt.Substring(0, alltxt.Length - Environment.NewLine.Length)
  114. Dim cleanText As String
  115. 'it removes the the last comma ","
  116. cleanText = alltxt.Remove(alltxt.Length - 1)
  117. Dim finalText As String
  118. 'combination of finalText with table name and Mysql ENGINE
  119. finalText = TBLCREATE & cleanText & ")ENGINE = MYISAM ;"
  120.  
  121. con.Open()
  122. With cmd
  123. .Connection = con
  124. .CommandText = finalText
  125. result = cmd.ExecuteNonQuery
  126. If result > 0 Then
  127. MsgBox("No Table has created!")
  128. Else
  129. MsgBox(txttblName.Text & " has created Successfully!")
  130. With Me
  131. .txttblName.ReadOnly = True
  132. .btnCreateTbl.Visible = False
  133. .btnAddtbl.Visible = True
  134. .dtgStructNewTbl.SendToBack()
  135. '.dtgStructNewTbl.Columns.Clear()
  136. End With
  137.  
  138.  
  139. End If
  140. End With
  141.  
  142.  
  143. Form1_Load(sender, e)
  144.  
  145. Catch ex As Exception
  146. MsgBox(ex.Message)
  147. End Try
  148. con.Close()
  149. End Sub
  150. End Class
To test this program, press “F5”.

Comments

Add new comment