java sql connection example
import java.sql.*;
class MySQLConnection{
public static final String DBNAME = "name_of_the_database"; // Like "testDB"
/** JDBC driver name and database URL */
public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
/** Gives access to all Databases */
static final String ALL_DBS_URL = "jdbc:mysql://localhost/?allowPublicKeyRetrieval=true&autoReconnect=true&useSSL=false";
/** Gives access to a given DB */
static final String GIVEN_DB_URL = "jdbc:mysql://localhost/"+DBNAME+"?allowPublicKeyRetrieval=true&autoReconnect=true&useSSL=false";
// Below are the USERNAME and PASSWORD used in mysql
public static final String USER = "myUserName";
public static final String PASS = "myGoodPassWord";
/** A variable for connecting to MySQL Server */
public static Connection conn = null;
/** A variable for Preparing Statements */
public static PreparedStatement ps = null;
public static void main(String[] args)
throws ClassNotFoundException, SQLException {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection with MySQL server
System.out.println("Connecting to all Databases path...");
conn = DriverManager.getConnection(ALL_DBS_URL, USER, PASS);
System.out.println("Connected to all Databases!");
// Test if there is the db in MySQL Server
// if not then create one
System.out.println("Testing if "+DBNAME+" exists...");
ps = conn.prepareStatement("CREATE DATABASE IF NOT EXISTS "+DBNAME+";");
ps.executeUpdate();
// Now db exists for sure!
// Open a connection with given DB
System.out.println("Connecting to "+DBNAME+" path...");
conn = DriverManager.getConnection(GIVEN_DB_URL, USER, PASS);
System.out.println("Connected to "+DBNAME+"!");
// then you can do all sort of queries that you want to do
}
}
0
0
public void commit() throws SQLException {
getConn().commit();
if (logger.isTraceEnabled()) {
logger.trace("Batch executor commit " + idx.get() + " rows");
}
idx.set(0);
}
Thank you!
0
0
Are there any code examples left?
New code examples in category Java
-
Java 2022-03-27 21:35:04 Sort string array in case insensitive order and case sensitive order java
-
Java 2022-03-27 21:25:10 java -jar -l resources\es.porperties -i ejemplo.txt -o inject.bin
-
Java 2022-03-27 21:20:21 Debug & Fix a 2-Dimensional Array Java Console Application
-
Java 2022-03-27 20:40:19 TreeSet headSet(E toElement) method in java
-
Java 2022-03-27 19:30:06 close keyboard android
-
Java 2022-03-27 19:20:40 java measure execution time
-
Java 2022-03-27 19:10:06 how to add cardview support in android studio
-
Java 2022-03-27 18:55:08 android studio lower case letters on a button