Data Access Question

Embed Size (px)

Citation preview

  • 7/31/2019 Data Access Question

    1/16

  • 7/31/2019 Data Access Question

    2/16

    On Wizard Completed, checkConfigure the MySQL Server Now and clickFinish.

    On MySQL Configuration Wizard, clickNext.

    On MySQL Server Instance Configuration, select Standard Configuration..

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/6.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/5.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/6.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/5.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/6.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/5.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/4.png
  • 7/31/2019 Data Access Question

    3/16

    On MySQL Server Instance Configuration, verify that all check boxes are checked on this page

    and clickNext. The first and second (Install As Windows Service and Launch the MySQLServer 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. ClickNext.

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/9.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/8.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/7.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/9.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/8.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/7.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/9.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/8.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/7.png
  • 7/31/2019 Data Access Question

    4/16

    On MySQL Server Instance Configuration, clickExecute to start the configuration.

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

    CONNECT TO THE SERVER AND CREATE DATABASEOn 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.

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/11.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/10.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/11.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/10.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/11.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part2/10.png
  • 7/31/2019 Data Access Question

    5/16

    Now I have connected to the MySQL Server. Next, create a database named world.

    CREATEDATABASE 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 recommendto 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 rootp

    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.

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part4/2.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part4/1.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part4/2.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part4/1.png
  • 7/31/2019 Data Access Question

    6/16

    GRANTSELECT,INSERT,UPDATE,DELETEON world.* TO 'worldUser'@'%';

    INSTALL MYSQL CONNECTOR NET

    Since we already installed Microsoft Visual Studio. Now we need to download and installMySQL Connector/Net which is a library for connect to MySQL Server from .NET Application.

    Setup MySQL Connector NetDownload MySQL Connector/Net 5.2 from mysql.com.

    Execute the downloaded file MySql.Data.msi. On Setup Welcome Screen, clickNext.

    On Choose Setup Type, click on Typical.

    On Ready to install MySQL Connector Net 5.2.5, clickInstall.

    http://dev.mysql.com/downloads/connector/net/5.2.htmlhttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/2.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/1.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part4/3.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/2.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/1.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part4/3.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/2.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/1.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part4/3.pnghttp://dev.mysql.com/downloads/connector/net/5.2.html
  • 7/31/2019 Data Access Question

    7/16

    When Setup has completed, clickFinish.

    Create Connection

    On Development PC, open Microsoft Visual Studio

    Create a New Windows Application Project SampleMySQL.

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/1.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/3.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/1.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/3.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/1.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part5/3.png
  • 7/31/2019 Data Access Question

    8/16

    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,itllthrow error. So we have to set the Copy Local property of the library file to True. ClickShow

    All Files icon.

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/3.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/2.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/3.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/2.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/3.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/2.png
  • 7/31/2019 Data Access Question

    9/16

    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

    2

    34

    5

    Private Sub Form1_Load(ByVal sender As System.Object, _

    ByVal e As System.EventArgs) Handles MyBase.Load

    TestConnection()End Sub

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/7.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/6.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/5.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/7.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/6.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/5.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/7.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/6.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/5.png
  • 7/31/2019 Data Access Question

    10/16

    67

    8

    9

    10

    1112

    1314

    15

    1617

    18

    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

    Code Explanation:Line 1-4: Simple Form_Load event that call TestConnection() method. The method is invokedwhen the form is loaded.

    Line: 7-17: Try-Catch scope. If there is any error in try scope, throws exception and goes tocatch 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.

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part6/8.png
  • 7/31/2019 Data Access Question

    11/16

  • 7/31/2019 Data Access Question

    12/16

    2324

    25

    26

    27

    2829

    3031

    32

    3334

    35

    36

    3738

    3940

    Dim cmd AsNew MySqlCommand(query, connection)

    connection.Open()

    Dim reader As MySqlDataReader

    reader = cmd.ExecuteReader()

    While reader.Read()Console.WriteLine((reader.GetString(0) & ", " & _

    reader.GetString(1)))

    EndWhile

    reader.Close()

    connection.Close()

    Catch ex As ExceptionConsole.WriteLine(ex.Message)

    End TryEndSub

    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 MySqlDataReaderobject.

    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 usingeverytime.Line 38: If there is any error in the method, send to console.

    The code will look similar as the figure below.

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part7/2.png
  • 7/31/2019 Data Access Question

    13/16

    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 anyresult sets returned will not be available.

    Update FunctionThis 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

    434445

    46

    4748

    49

    5051

    52

    53

    5455

    56

    57

    58

    Function updateRecord(ByVal query AsString) AsInteger

    TryDim rowsEffected AsInteger = 0

    Dim connection AsNew MySqlConnection(connStr)

    Dim cmd AsNew MySqlCommand(query, connection)

    connection.Open()

    rowsEffected = cmd.ExecuteNonQuery()

    connection.Close()

    Return rowsEffectedCatch ex As Exception

    Console.WriteLine(ex.Message)

    End Try

    EndFunction

    Code Explanation:Line 50: The code is similar to retrieve data section only it call ExecuteNonQuery() method andthe return value is affected rows.

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part7/3.png
  • 7/31/2019 Data Access Question

    14/16

    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 newrecord to Country table on world database.

    Then, output the affected rows to console.

    14Console.WriteLine(updateRecord("INSERT INTO Country (Code, Name) VALUES

    ('AAA','Test Name')"))

    UPDATE

    The UPDATE command belows change Name to Test2 on row which has code = AAA. Andoutput the affected rows to console.

    15Console.WriteLine(updateRecord("UPDATE Country SET Name='Test2' WHERE Code

    ='AAA'"))

    DELETE

    The DELETE command deletes a record which has code equals AAA. And output the affectedrows 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

    hereSampleMySQL (zip format). The project was created on Microsoft Visual Studio 2005.

    http://www.linglom.com/downloads/SampleMySQL.ziphttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part7/5.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part7/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part7/5.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part7/4.pnghttp://www.linglom.com/downloads/SampleMySQL.zip
  • 7/31/2019 Data Access Question

    15/16

    Open the Design view ofForm1.

    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 toretriveData() method except that it use MySqlDataAdapter rather than MySqlDataReader.

    1

    2

    34

    5

    Public Sub retriveDataToDataGrid()

    Try

    Dim query As String = "SELECT * FROM Country"Dim connection As New MySqlConnection(connStr)

    Dim da As New MySqlDataAdapter(query, connection)

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/3.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/2.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/1.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/3.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/2.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/1.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/3.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/2.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/1.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/4.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/3.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/2.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/1.png
  • 7/31/2019 Data Access Question

    16/16

    67

    8

    9

    10

    1112

    1314

    15

    1617

    Dim ds As New DataSet()

    If da.Fill(ds) Then

    DataGridView1.DataSource = ds.Tables(0)

    End If

    connection.Close()

    Catch ex As Exception

    Console.WriteLine(ex.Message)

    End TryEnd 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.

    http://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/7.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/6.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/5.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/7.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/6.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/5.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/7.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/6.pnghttp://www.linglom.com/images/Windows/Programming/VBNET-MySQL/Part8/5.png