Getting started with MySQL and Java

UPDATED: 18 February 2013

                MySQL is an opensource Relational Database Management System. Now a days it is used by most of  website and software. Apart from that if you are Entrepreneur it helps to cut the cost. I personally use MySQL on my website. 

                Some of you have any miss guided news about MySQL here is your answer. Facebook uses MySQL. Read more about it on MySQL website : http://www.mysql.com/customers/view/?id=757

Facebook and MySQL statistics : 
  • Facebook process 60 million request in one second.
  • Facebook maintains database of more than 800 million users ; 500 million of them visits facebook daily
  • 350 million mobile user
  • 7 million application integrated with facebook platform.
  • Hope that's enough for you to understand what MySQL can handle...

Lets move to codding part quickly. Before you jump to any code download required software. Follow the links below to quick start : 

Database : ( MySQL )
  • MySQL Server
  • All of our support connectors
  • Workbench and sample models ( Provide database access using GUI )
  • MySQL Notifier
  • MySQL for Excel
  • MySQL for Visual Studio
  • Sample databases
  • Documentation

Library :

  • .jar file to connect database


Hope you have installed MySQL in your system. Now let me show you how you can connect to MySQL database with below code snippet.
import java.sql.*; // import SQL connection class
public final class MySQLDemo {
    public static final String dbhost = "jdbc:mysql://localhost:3306/javaQuery"; //javaQuery is schema name
    public static final String dbusername = "root";
    public static final String dbpassword = "root";
    public static final String dbdriver = "com.mysql.jdbc.Driver";

    public static void main(String[] args) {
        try {
            Class.forName(dbdriver); // Load driver
            Connection con = DriverManager.getConnection(dbhost, dbusername, dbpassword); // Create connection to database
            PreparedStatement selectData_stmt = con.prepareStatement("select * from DemoJavaQuery"); // Prepare query
            ResultSet selectData_rs = selectData_stmt.executeQuery(); // execute query and get data
            while(selectData_rs.next()){ //executes till last row available
                System.out.println(selectData_rs.getString("column_name")); // print data
            }
            /*
             * Close connection if you don't need further.
             * If you don't close it will create problem when you deal with large application
            */
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

For best practice read more on database:
http://www.javaquery.com/2013/02/preparedstatement-best-practice-of.html
http://www.javaquery.com/search/label/Database

0 comments :