Sunday 13 December 2015

How to connect to My SQL and Postgres through Java Programs

My SQL Connection String in JAVA :

import java.sql.Connection;
import java.sql.DriverManager;

public class Main {
  public static void main(String[] argv) throws Exception {
    String driver = "com.mysql.jdbc.Driver";
    String connection = "jdbc:mysql://localhost:3306/YourDBName";
    String user = "root";
    String password = "root";
    Class.forName(driver);
    Connection con = DriverManager.getConnection(connection, user, password);
    if (!con.isClosed()) {
      con.close();
    }
  }
}

Postgres Connection String in JAVA :

String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","fred");
props.setProperty("password","secret");
props.setProperty("ssl","true");
Connection conn = DriverManager.getConnection(url, props);

OR-
String url = "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";
Connection conn = DriverManager.getConnection(url);
user = String
The database user on whose behalf the connection is being made.

password = String
The database user's password.

No comments:

Post a Comment