假设mysql进程已经启动(默认端口3306),登录该实例的mysql账号为:root,密码为:root,该实例里面的目标数据库名字为test,则Java代码如下:
说明:实例即是instance,所有的类在使用前都需要建立一个instance
package ione.core.login;
import java.lang.System;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
//Notice:do not inport com.mysq.jdbc.*
//or you will have problems!
public class ConnectDB {
public static void main(String[] args) {
//1.使用Class类的forName()方法注册并建立一个Driver实例
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
ex.printStackTrace();
//System.out.println(ex); //System.out.println(ex) = System.out.println("SQLException:" + ex.getMessage())
}
Connection conn = null;
//2.使用DriverManager的getConnection()方法建立一个Connection实例conn
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" +
"user=root&password=root");
} catch (SQLException ex){
ex.printStackTrace();
}
Statement stmt = null;
ResultSet rs = null;
//3.使用Connection对象(即conn)的createStatement()方法创建一个Statement对象;
// createStatement()方法的第一个参数:设置ResultSet的数据类型为动态或者静态 ;
// createStatement()方法的第二个参数:设置ResultSet的并发模式。
try {
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY);
//4.使用Statement对象(即stmt)的executeQuery()方法执行sql语句,并把返回的
//结果集赋值给ResultSet的对象rs
rs = stmt.executeQuery("select * from users;");
if (stmt.execute("select * from users;")) {
rs = stmt.getResultSet();
}
//5.打印结果集中的数据
if (rs.next()) {
System.out.println("id\t" + "username\t" + "password\t" + "created_time\t\t" + "update_time\t");
System.out.print(rs.getString("id") + "\t");
System.out.print(rs.getString("username") + "\t\t");
System.out.print(rs.getString("password") + "\t\t");
System.out.print(rs.getString("created_time") + "\t");
System.out.println(rs.getString("updated_time"));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
//6.在final{}块中释放资源,释放的顺序与创建实例的顺序恰好相反
finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {}
stmt = null;
}
}
} //End of main
} //End of the Java class