jdbcUtil02.java
//单例模式
public final class jdbcUtil02 {
static String url = "jdbc:mysql://localhost:3306/jdbc";
static String username = "root";
static String password = "root";
//private static jdbcUtil02 instance = new jdbcUtil02();
private static jdbcUtil02 instance= null;
//构造私有化
private jdbcUtil02(){
}
//提供一个公共的static方法
public static jdbcUtil02 getInstance(){
if (instance==null) {
//延迟加载 使用的时候new
//处理并发问题 可以加锁
synchronized (jdbcUtil02.class) {
instance = new jdbcUtil02();
}
}
return instance;
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
public static void free(Statement st, Connection conn, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
}
}
}
}
}
package com.sg.test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
public class JdbcCRUDTest {
// 查询
@Test
public void select() throws Exception {
Connection conn = jdbcUtil02.getInstance().getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from user");
while (rs.next()) {
System.out.println("id:" + rs.getInt("id") + "\n name:"
+ rs.getString("name") + "\n age:" + rs.getInt("age")
+ "\n sex" + rs.getString("sex") + "\n brithday:"
+ rs.getDate("brithday"));
}
// 关闭资源
jdbcUtil02.free(st, conn, rs);
}
//添加
@Test
public void insert() throws Exception {
Connection conn = jdbcUtil02.getInstance().getConnection();
Statement st = conn.createStatement();
String sql = "insert into user values(4,'name1',20,'nan','1992-12-28')";
int i = st.executeUpdate(sql);
System.out.println("i = "+i);
}
//修改
@Test
public void update() throws Exception {
Connection conn = jdbcUtil02.getInstance().getConnection();
Statement st = conn.createStatement();
String sql = "update user set age = 30 where id = 1";
int i = st.executeUpdate(sql);
}
//删除
@Test
public void delete() throws Exception {
Connection conn = jdbcUtil02.getInstance().getConnection();
Statement st = conn.createStatement();
String sql = "delete from user where id > 2";
int i = st.executeUpdate(sql);
}
}