Sunteți pe pagina 1din 6

Connecting VB.Net to Mysql Software needed VB.NET MySQL MySQL Connector/Net 5.

2 Creating Connection

Create Connection
1. On Development PC, open Microsoft Visual Studio 2005.

2. Create a New Windows Application Project SampleMySQL.

3. First, I need to add a MySQL library. Right-click on the project name (SampleMySQL) ->

Add Reference.

4. On Add Reference, select MySQL.Data on .NET tab.

5. By default, the reference library (MySQL.Data) wont be copied to the output directory.

That means when you deploy the application on other PC which doesnt have the library installed, itll throw error. So I have to set the Copy Local property of the library file to True. Click Show All Files icon.

6. Expand References -> Select MySQL.Data -> Change Copy Local property to True.

7. Now its time to coding the application. First, I have to import a namespace. Open the Code View and add this line on the top.
Imports MySql.Data.MySqlClient

8. Add these code to the Class.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load TestConnection() End Sub Public Sub TestConnection() Try Dim connStr As String = "Database=world;" & _ "Data Source=192.168.125.21;" & _ "User Id=worldUser;Password=worldpassword" Dim connection As New MySqlConnection(connStr) connection.Open() connection.Close() MsgBox("Connection is okay.") Catch ex As Exception MsgBox(ex.Message) End Try End Sub

9. Code Explanation: o Line 1-4: Simple Form_Load event that call TestConnection() method. The method is invoked when the form is loaded. o Line: 7-17: Try-Catch scope. If there is any error in try scope, throws exception and goes to catch scope. o Line: 8-10: A connection string represents configuration for connect to MySQL Server. Common attributes are: 1. Database. The database to be used after a connection is opened. 2. Data Source. The name of the MySQL server to which to connect. 3. Port. The port MySQL is using to listen for connections. The default value is 3306 4. User ID. The user that use to connect to the database on MySQL Server 5. Password. Password of the user. 6. Connection Timeout. Time to wait while trying to establish a connection before terminating the attempt and generating an error. o Line 11: Create MySqlConnection object and assign connectionString property. o Line 12-13: Test open and close the connection to the database on MySQL Server. o Line 14: If there is no error, show a success message. o Line 16: Show the error message.

10. Next, test the code by run the application. If the connection is successfully connected and

disconnected. Youll see the message Connection is okay.

11. If something wrongs, youll see message other than the previous step. The figure below is

the example that mistyped the database name in the connection string.

Coding Part

Imports MySql.Data Imports MySql.Data.MySqlClient Module conn Public connStr As String = "Database=nia-isf;" & _ "Data Source=127.0.0.1;" & _ "User Id=root;Password=;" & _ "Connection Timeout=20" Public cmd As New MySqlCommand Public da As New MySqlDataAdapter Public conn As New MySqlConnection(connStr) Public Sub TestConnection() Try conn.Open() conn.Close() Catch ex As Exception MsgBox("Error Connecting to Server", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "ISF") End Try End Sub End Module ////////////////////////////////////////////////////////////////// ***Used to display the data to a data grid view Public Sub loaddata() Try TestConnection() Dim conn As New MySqlConnection(connStr) cmd.Connection = conn conn.Open() cmd.CommandText = "SELECT lot_no as 'LOT NO', division as 'DIVISION',type as 'TYPE',landowner_lastname as 'LAND OWNER LASTNAME',landowner_firstname as 'LAND OWNER FIRSTNAME',owner_address as 'ADDRESS',tenant_lastname as 'TENANTS LASTNAME',tenant_firstname as 'TENANTS FIRSTNAME',tenant_address as 'TENANTS ADDRESS',location as 'LOCATION', actual_lot_area as 'ACTUAL LOT AREA',wrft as 'WRFT',ia_name as 'IA NAME',canal_name as 'NAME OF CANAL',tsa as 'TSA' FROM tblfarmer" ' cmd.CommandText = "SELECT * FROM tblfarmer" da.SelectCommand = cmd Dim ds As New DataSet Dim cb As MySqlCommandBuilder = New MySqlCommandBuilder(da) da.Fill(ds, "tblfarmer") frmviewfarmers.dgvfarmers.DataSource = ds.Tables(0) 'frmviewemployee.Label1.Text = "Total no. of Records:" & frmviewemployee.dgvviewemployee.Rows.Count conn.Close() Catch ex As Exception End Try End Sub Used to add data

Public Sub addfarmer() Dim conn As New MySqlConnection(connStr) cmd.Connection = conn conn.Open() cmd.CommandText = "INSERT INTO tblfarmer (lot_no,division,type,landowner_lastname,landowner_firstname,owner_address,te nant_lastname,tenant_firstname,tenant_address,location,actual_lot_area,wrft,i a_name,canal_name,tsa)VALUES (" _ & "'" & frmaddfarmer.txtlotno.Text & "', " _ & "'" & frmaddfarmer.txtdivision.Text & "'," _ & "'" & frmaddfarmer.txttype.Text & "'," _ & "'" & frmaddfarmer.txtlastname.Text & "'," _ & "'" & frmaddfarmer.txtfirstname.Text & "'," _ & "'" & frmaddfarmer.txtaddress.Text & "'," _ & "'" & frmaddfarmer.txttenantlname.Text & "'," _ & "'" & frmaddfarmer.txttenantfname.Text & "'," _ & "'" & frmaddfarmer.txttenantaddress.Text & "'," _ & "'" & frmaddfarmer.txtlocation.Text & "'," _ & "'" & frmaddfarmer.txtlotarea.Text & "'," _ & "'" & frmaddfarmer.txtwrft.Text & "'," _ & "'" & frmaddfarmer.txtia.Text & "'," _ & "'" & frmaddfarmer.txtcanal.Text & "'," _ & "'" & frmaddfarmer.txttsa.Text & "')" cmd.ExecuteNonQuery() conn.Close() End Sub

S-ar putea să vă placă și