//静态模式
package cn.eboy.jdbc;
import java.sql.*;
public final class JdbcUtils {
private static String url = "jdbc:mysql://127.0.0.1:3306/ssh?useUnicode=true&characterEncoding=GBK";
private static String user = "root";
private static String password = "123456";
private JdbcUtils(){
}
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, user, password);
}
public static void free(ResultSet rs, Statement st, Connection conn){
try{
if (rs != null){
rs.close();
}
}catch (SQLException e){
e.printStackTrace();
}finally{
try{
if (st != null){
st.close();
}
}catch (SQLException e){
e.printStackTrace();
}finally{
if (conn != null){
try{
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}
}
}
//JDBC 查询,增加,修改,删除
package cn.eboy.jdbc;
import cn.eboy.jdbc.JdbcUtils;
public class CRUD {
public static void main(String[] args) {
try {
insert();
select();
update();
delete();
} catch (Exception e) {
e.printStackTrace();
}
}
static void select() throws Exception {
java.sql.Connection conn = null;
java.sql.Statement st = null;
java.sql.ResultSet rs = null;
String sql = "select id, username, password from user";
try {
//2.建立连接,可选指定编码及字符集
conn = JdbcUtils.getConnection();
//3.创建语句
st = conn.createStatement();
//4.执行语句
rs = st.executeQuery(sql);
//5.处理结果
while (rs.next()){
System.out.println(rs.getString("id") + "\t" +
rs.getObject("username") + "\t" +
rs.getObject("password"));
}
} finally {
JdbcUtils.free(rs, st, conn);
}
}
static void insert() throws Exception {
java.sql.Connection conn = null;
java.sql.Statement st = null;
java.sql.ResultSet rs = null;
String sql = "insert into user(username, password)values('eboy', 'dxawihty')";
try {
//2.建立连接,可选指定编码及字符集
conn = JdbcUtils.getConnection();
//3.创建语句
st = conn.createStatement();
//4.执行语句
int i = st.executeUpdate(sql);
//5.处理结果
System.out.println("Result: " + i);
} finally {
JdbcUtils.free(rs, st, conn);
}
}
static void update() throws Exception {
java.sql.Connection conn = null;
java.sql.Statement st = null;
java.sql.ResultSet rs = null;
String sql = "update user set password='gxy850318' where username = 'eboy'";
try {
//2.建立连接,可选指定编码及字符集
conn = JdbcUtils.getConnection();
//3.创建语句
st = conn.createStatement();
//4.执行语句
int i = st.executeUpdate(sql);
//5.处理结果
System.out.println("Result: " + i);
} finally {
JdbcUtils.free(rs, st, conn);
}
}
static void delete() throws Exception {
java.sql.Connection conn = null;
java.sql.Statement st = null;
java.sql.ResultSet rs = null;
String sql = "delete from user";
try {
//2.建立连接,可选指定编码及字符集
conn = JdbcUtils.getConnection();
//3.创建语句
st = conn.createStatement();
//4.执行语句
int i = st.executeUpdate(sql);
//5.处理结果
System.out.println("Result: " + i);
} finally {
JdbcUtils.free(rs, st, conn);
}
}
}