Sunday, July 7, 2013

How To Connect MySQL Database Using Java

Hello

In this article, I'll show you how to connect MySQL database using java. For this, you should configure the settings about MySQL connector in the JAVA IDE first. So all things what we need are;


  • IDE (NetBeans or EClipse is so good!)
  • MySQL Connector

  • MySQL Connector is a jar file which is so small size. You can download MySQL Connector here and check this line up:
    JDBC Driver for MySQL (Connector/J)
    After downloading, you have to introduce IDE and Connector. I use NetBeans. Because of I will show you how to introduce on the NetBeans already. Actually It doesn't matter which program has used. For that reason This process is the same for EClipse.

    Screen views given above show us the process about introducing. You click OK and it's finish. Your MySQL driver and JAVA IDE know each other from on now. Let's create a db class on there.
    void vt() {
            Connection conn = null;
            String hostName = "jdbc:mysql://localhost:3306/";
            String dbName = "DatabaseName";
            String driver = "com.mysql.jdbc.Driver";
            String userName = "root";
            String password = "*****";
            try {
                conn = DriverManager.getConnection(
                    hostName+dbName,userName,password);
                System.out.println("Connected to the database");
                Statement st = conn.createStatement();
                ResultSet result = st.executeQuery("SELECT * FROM  test");
                while (result.next()) {
                   int id = result.getInt("id");
                   String name = result.getString("name");
                   System.out.println(id + "\t" + name);
            }
                conn.close();
            } catch (Exception e) {
                System.out.println("No Connection!");
            }
    }
    

    In the try..catch debugging part, if there is no connection, You are going to see "No Connection!" alert on the screen. If not, You'll get names of the test table from your database. This code given above is not so good, but useful. If you want to code better, you can use OOP for example. Create a class of database connection, and use it each time connection.
    See you next article!

    No comments:

    Post a Comment

    Thanks