Sie sind auf Seite 1von 16

Using MySQL as the back end, data access in VB.

net can be done by following these steps; Setup MySQL Server Create Database on MySQL Server. Create & Grant MySQL User Account - create a new user and grant privileges to certain database on the MySQL Server. Install MySQL Connector/NET - this can be downloaded from Create Connection - establish a connection between VB.NET and MySQL. Perform SQL Operations from VB.NET to MySQL. For instance, send query as SELECT, INSERT, UPDATE to a database. Display Result on GUI - display the query data on GUI using datagrid. SETUP MYSQL SERVER Download MySQL Community Edition from Double-click the setup file mysql-essential-5.1.30-win32.msi. Click Next.

On Setup Type, select Typical. Click Next.

On Ready to Install the Program, click Install.

On Wizard Completed, check Configure the MySQL Server Now and click Finish.

On MySQL Configuration Wizard, click Next.

On MySQL Server Instance Configuration, select Standard Configuration..

On MySQL Server Instance Configuration, verify that all check boxes are checked on this page and click Next. The first and second (Install As Windows Service and Launch the MySQL Server automatically) check boxes configure MySQL as a Windows service so that you dont have to login to the PC and start MySQL Server manually, itll start when the PC is on automatically.

On MySQL Server Instance Configuration, check only the upper check box Modify Security Settings and enter the root password. The root user is the default user on MySQL who has all privileges on the MySQL Server. Here, I set the roots password to password. Click Next.

On MySQL Server Instance Configuration, click Execute to start the configuration.

When the configuration is done, click Finish to complete install and configure MySQL Server.

CONNECT TO THE SERVER AND CREATE DATABASE On the database PC, open command-line mode. Type below command to connect to the MySQL Server using MySQLs root account. mysql -u root -p The parameter -p makes MySQL ask you to enter the password. Then, type the roots password. Its password.

Now I have connected to the MySQL Server. Next, create a database named world. CREATE DATABASE world; Then, change the default database to the created database. USE world; CREATE & GRANT MYSQL USER ACCOUNT By default, the root account on MySQL Server has all privileges on every tables on MySQL Server but only localhost can have accessed (remote access is not allowed) and it is recommend to use other user account rather than root account to perform operations on MySQL Server (for security issue). Therefore, we should create a new user account on MySQL and grant at least privileges for the account as possible. Create User account and password Open Command-line and type mysql -u root p Itll ask for the password. Type roots password.

To Create a User Account on MySQL Server, use this format: CREATE USER username IDENTIFIED BY 'password' Lets create MySQL User Account worldUser with password worldpassword. CREATE USER worldUser IDENTIFIED BY 'worldpassword';

Grant Privileges on User Account To grant privileges on MySQL User Account, use this format: GRANT privileges ON database.table TO 'username'@'host' Lets grant privileges on worldUser to allow SELECT, INSERT, UPDATE and DELETE on world database from any machine.


INSTALL MYSQL CONNECTOR NET Since we already installed Microsoft Visual Studio. Now we need to download and install MySQL Connector/Net which is a library for connect to MySQL Server from .NET Application. Setup MySQL Connector Net Download MySQL Connector/Net 5.2 from Execute the downloaded file MySql.Data.msi. On Setup Welcome Screen, click Next.

On Choose Setup Type, click on Typical.

On Ready to install MySQL Connector Net 5.2.5, click Install.

When Setup has completed, click Finish.

Create Connection On Development PC, open Microsoft Visual Studio

Create a New Windows Application Project SampleMySQL.

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

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

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 we have to set the Copy Local property of the library file to True. Click Show All Files icon.

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

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

Add these code to the Class. 1 Private Sub Form1_Load(ByVal sender As System.Object, _ 2 ByVal e As System.EventArgs) Handles MyBase.Load 3 TestConnection() 4 End Sub 5

6 Public Sub TestConnection() 7 Try 8 Dim connStr As String = "Database=world;" & _ 9 "Data Source=;" & _ 10 "User Id=worldUser;Password=worldpassword" 11 Dim connection As New MySqlConnection(connStr) 12 connection.Open() 13 connection.Close() 14 MsgBox("Connection is okay.") 15 Catch ex As Exception 16 MsgBox(ex.Message) 17 End Try 18 End Sub Code Explanation: Line 1-4: Simple Form_Load event that call TestConnection() method. The method is invoked when the form is loaded. Line: 7-17: Try-Catch scope. If there is any error in try scope, throws exception and goes to catch scope. Line: 8-10: A connection string represents configuration for connect to MySQL Server. Common attributes are: Database. The database to be used after a connection is opened. Data Source. The name of the MySQL server to which to connect. Port. The port MySQL is using to listen for connections. The default value is 3306 User ID. The user that use to connect to the database on MySQL Server Password. Password of the user. Connection Timeout. Time to wait while trying to establish a connection before terminating the attempt and generating an error. Line 11: Create MySqlConnection object and assign connectionString property. Line 12-13: Test open and close the connection to the database on MySQL Server. Line 14: If there is no error, show a success message. Line 16: Show the error message.

Next, test the code by run the application. If the connection is successfully connected and disconnected. Youll see the message Connection is okay.

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.

PERFORM SQL OPERATIONS To perform basic SQL operations (SELECT, INSERT, UPDATE and DELETE) on the world database. Declare a Connection String 1 Private connStr As String = "Database=world;" & _ 2 "Data Source=;" & _ 3 "User Id=worldUser;Password=worldpassword;" & _ 4 "Connection Timeout=20" The code will look similar as the figure below.

Retrieve data from database 19 Public Sub retriveData() 20 Try 21 Dim query As String = "SELECT * FROM Country" 22 Dim connection As New MySqlConnection(connStr)

23 Dim cmd As New MySqlCommand(query, connection) 24 25 connection.Open() 26 27 Dim reader As MySqlDataReader 28 reader = cmd.ExecuteReader() 29 30 While reader.Read() 31 Console.WriteLine((reader.GetString(0) & ", " & _ 32 reader.GetString(1))) 33 End While 34 35 reader.Close() 36 connection.Close() 37 Catch ex As Exception 38 Console.WriteLine(ex.Message) 39 End Try 40 End Sub Code Explanation: Line 21: Create a query variable as string. Line 22: Create a MySQLConnection object with the defined connection string in global as parameter. Line 23: Create a MySQLCommand object with previous 2 variables as parameters. Line 25: Open a connection to MySQL Server using the defined connection string. Line 27-28: Call ExecuteReader() method and assign the result to MySqlDataReader object. Line 30-33: Looping on MySqlDataReader object to get results to the console. Line 35-36: Close the reader and connection. I recommend to close these objects after using everytime. Line 38: If there is any error in the method, send to console. The code will look similar as the figure below.

The result of the query shows the first and second columns in the output window.

Update Record on Database Coding on INSERT, UPDATE and DELETE SQL operations are identical except only sql command that is executed. When we perform these operations to database, there is no need to get records from the database. So we use ExecuteNonQuery() Method from MySqlCommand Class. For INSERT, UPDATE and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1. Note: You can use ExecuteNonQuery to perform any type of database operation, however any result sets returned will not be available. Update Function This function accepts a parameter as sql command and send to execute on MySQL Server. So the function can be used for INSERT, UPDATE and DELETE operations also any operation that doesnt need a return result sets. Also, it returns an integer value of affected rows. 42 Function updateRecord(ByVal query As String) As Integer 43 Try 44 Dim rowsEffected As Integer = 0 45 Dim connection As New MySqlConnection(connStr) 46 Dim cmd As New MySqlCommand(query, connection) 47 48 connection.Open() 49 50 rowsEffected = cmd.ExecuteNonQuery() 51 52 connection.Close() 53 54 Return rowsEffected 55 Catch ex As Exception 56 Console.WriteLine(ex.Message) 57 End Try 58 End Function Code Explanation: Line 50: The code is similar to retrieve data section only it call ExecuteNonQuery() method and the return value is affected rows.

The function code will look similar as the figure below.

INSERT To execute INSERT command, try the statement below. The sql command will insert a new record to Country table on world database. Then, output the affected rows to console. Console.WriteLine(updateRecord("INSERT INTO Country (Code, Name) VALUES 14 ('AAA','Test Name')")) UPDATE The UPDATE command belows change Name to Test2 on row which has code = AAA. And output the affected rows to console. Console.WriteLine(updateRecord("UPDATE Country SET Name='Test2' WHERE Code 15 ='AAA'")) DELETE The DELETE command deletes a record which has code equals AAA. And output the affected rows to console. 16 Console.WriteLine(updateRecord("DELETE FROM Country WHERE Code ='AAA'")) When we have run the application with the 3 statements above, the output window shows the row affected of each statement as the figure below.

Step-by-step Ill continue from the previous post. You can download a project file from the previous post at here SampleMySQL (zip format). The project was created on Microsoft Visual Studio 2005.

Open the Design view of Form1.

Drag DataGridView tool from the Toolbox window to empty area on the form. Note: If you cant find Toolbox window, select View -> Toolbox.

The DataGridView is placed on the form. The dark background indicates the area of DataGridViews object. On Properties window, you see the default name is DataGridView1.

Back to the Forms code view. Comment all the lines in Form1_Load method. These are the code from the previous post which I dont want it to be executed.

Copy the code below to the form as a new method. Notice that this method is similar to retriveData() method except that it use MySqlDataAdapter rather than MySqlDataReader. 1 Public Sub retriveDataToDataGrid() 2 Try 3 Dim query As String = "SELECT * FROM Country" 4 Dim connection As New MySqlConnection(connStr) 5 Dim da As New MySqlDataAdapter(query, connection)

6 Dim ds As New DataSet() 7 8 If da.Fill(ds) Then 9 DataGridView1.DataSource = ds.Tables(0) 10 End If 11 12 connection.Close() 13 14 Catch ex As Exception 15 Console.WriteLine(ex.Message) 16 End Try 17 End Sub Code Explanation: Line 3-5: Create New MySqlDataAdapter object with some parameters. Line 6: Create an empty data set. Line 8-10: Fills a data set and set data source of DataGridView1 to a table in the data set. Line 12: Close the connection.

Add code to the Form1_Load method to call retriveDataToDataGrid() when the form is loaded.

Run the project. Youll see the result on DataGridView on Windows form. You may adjust the size of DataGridView to suit your screen.