Tuesday 13 September 2011

My sql Connection with Java

 import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
    System.out.println("MySQL Connect Example.");
   
    try {
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/"; // Connection url for mysql
    String dbName = "test";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "";
   
      Class.forName(driver).newInstance();
      conn = DriverManager.getConnection(url+dbName,userName,password);
      System.out.println("Connected to the database");
      conn.close();
      System.out.println("Disconnected from database");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

Run this program you need
mysql-connector-java-5.1.13-bin.jar

If you connect with oracle than Connection url is : "jdbc:oracle:thin:@localhost:1521:oracle"

"oracle" is a database

No comments:

Post a Comment