java sql connection code example
Example 1: java connect to mysql
import java.sql.*;
class MySqlConn{
public static void main(String args[]){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://
localhost:3306/databasename","username","password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp");
con.close();
}catch(Exception ex){
System.out.println(ex);
}
}
}
Example 2: java sql connection example
import java.sql.*;
class MySQLConnection{
public static final String DBNAME = "name_of_the_database";
public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String ALL_DBS_URL = "jdbc:mysql://localhost/?allowPublicKeyRetrieval=true&autoReconnect=true&useSSL=false";
static final String GIVEN_DB_URL = "jdbc:mysql://localhost/"+DBNAME+"?allowPublicKeyRetrieval=true&autoReconnect=true&useSSL=false";
public static final String USER = "myUserName";
public static final String PASS = "myGoodPassWord";
public static Connection conn = null;
public static PreparedStatement ps = null;
public static void main(String[] args)
throws ClassNotFoundException, SQLException {
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to all Databases path...");
conn = DriverManager.getConnection(ALL_DBS_URL, USER, PASS);
System.out.println("Connected to all Databases!");
System.out.println("Testing if "+DBNAME+" exists...");
ps = conn.prepareStatement("CREATE DATABASE IF NOT EXISTS "+DBNAME+";");
ps.executeUpdate();
System.out.println("Connecting to "+DBNAME+" path...");
conn = DriverManager.getConnection(GIVEN_DB_URL, USER, PASS);
System.out.println("Connected to "+DBNAME+"!");
}
}