Wednesday, August 18, 2010

Creating DataBase Connection in MySQL

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package db;

import java.sql.*;

/**
 *
 * @author subinsuresh
 */
public class dbconnection {

    Statement stmt;
    Connection con;

    public void start() {
        try {
            ResultSet rs;
            //Register the JDBC driver for MySQL.
            Class.forName("com.mysql.jdbc.Driver");
            /*
             * Define URL of database server for database named ems on the localhost      
             * with the default port number 3306.      
             */
           String url = "jdbc:mysql://localhost:3306/ems";
            /*
             * Get a connection to the database for a user named root with the password
             * subin, which is password spelled backwards.      
             */
         con = DriverManager.getConnection(url, "root", "subin");

            //Display URL and connection information
            System.out.println("URL: " + url);
            System.out.println("Connection: " + con);
        //Get a Statement object
        stmt = con.createStatement();
        //Query the database, storing the result in an object of type ResultSet
         rs = stmt.executeQuery("SELECT * from tablename");
     } catch (Exception e) {
            e.printStackTrace();
        }//end catch
    }

    public Statement getstatement() throws SQLException {
      stmt=con.createStatement();
      return stmt;
    }
}

No comments:

Post a Comment