what is sql connection con java code example
Example: 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+"!");
}
}