一、导入mysql 所需的jar包
二、创建一个DB类
package com.pazz.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* @author pazz
* @create 2017年5月11日 下午1:25:08
*/
public class DbHelper {
private static final String cname = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/test";
private static final String user = "root";
private static final String password = "sa123";
// 加载驱动
static {
try {
Class.forName(cname);
} catch (Exception e) {
e.printStackTrace();
}
}
// 创建数据库连接
public static Connection getcon() {
Connection con = null;
try {
con = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
// 关闭数据库连接
public static void myClose(Connection con) {
try {
if (con != null && !con.isClosed()) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 关闭数据库连接,执行对象
public static void myClose(Connection con, PreparedStatement ps) {
try {
if (con != null && !con.isClosed()) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 关闭数据库连接,执行对象.查询对象
public static void myClose(Connection con, PreparedStatement ps, ResultSet rs) {
try {
if (con != null && !con.isClosed()) {
con.close();
}
if (ps != null) {
ps.close();
}
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、连接测试
package com.pazz.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author pazz
* @create 2017年5月11日 下午1:31:30
*/
public class TestJDBC {
private Connection connection;
private PreparedStatement ps;
private ResultSet rs;
@Test
public void testJdbc() {
try {
ps = connection.prepareStatement("select * from person");
rs = ps.executeQuery();
while(rs.next()){
System.out.println("pid: "+rs.getInt(1)+" pname: "+rs.getString(2)+" page: "+rs.getInt(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Before
public void before(){
connection = DbHelper.getcon();
System.out.println("connection: "+connection);
}
@After
public void after(){
try {
DbHelper.myClose(connection, ps, rs);
System.out.println(connection.isClosed());
System.out.println(ps.isClosed());
System.out.println(rs.isClosed());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}