Example of MySQL JAVA
1. Download MySQL and run the server.
2. Create one table in one database.
3. Download JAVA jdbc jar, ex, mysql-connector-java-5.1.25, and import it in the JAVA project.
4. The JAVA example as follows,
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLConnection {
private static MySQLConnection connection;
public static MySQLConnection getInstance() {
if (connection != null) {
return connection;
} else {
return new MySQLConnection();
}
}
private MySQLConnection() {}
private final static String username = "palmer";
private final static String pwd = "123456";
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/test";
private Connection conn = null;
private Statement stmt = null;
public boolean makeConnection() {
stmt = null;
// STEP 1: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
// STEP 2: make a connection to the database
conn = DriverManager.getConnection(DB_URL, username, pwd);
stmt = conn.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public void releaseConnection() {
try {
// STEP 4: release connection and statement.
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet query(String sqlStr) {
try {
// STEP 3: do database operations.
ResultSet set = stmt.executeQuery(sqlStr);
while (set.next()) {
int id = set.getInt(1);
String name = set.getString(2);
System.out.println(id + " " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void main(String args[]){
MySQLConnection connection = MySQLConnection.getInstance();
if(connection.makeConnection()){
connection.query("select * from test_1;");
connection.releaseConnection();
}
}
}