首页 > 代码库 > JavaWeb学习总结-10 JDBC的CRUD
JavaWeb学习总结-10 JDBC的CRUD
一 常用JDBC API
1 搭建测试环境
MySQL数据库测试脚本
create database jdbcStudy character set utf8 ;use jdbcStudy;create table users( id int primary key, name varchar(40), password varchar(40), email varchar(60), birthday date)ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;insert into users(id,name,password,email,birthday) values(1,‘zhansan‘,‘123456‘,‘zs@163.com‘,‘2016-09-01‘);insert into users(id,name,password,email,birthday) values(2,‘lisi‘,‘123456‘,‘lisi@163.com‘,‘2016-09-02‘);insert into users(id,name,password,email,birthday) values(3,‘wangwu‘,‘123456‘,‘wangwu@163.com‘,‘2016-09-03‘);
把链接数据库的操作封装成一个公共函数:
// 取得一个Connction private Connection getConnection() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8";
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, "root", "123456");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
2 Statement对象
Jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。
Statement对象的executeUpdate方法,用于向数据库发送增、删、改的sql语句,executeUpdate执行完后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)。
Statement.executeQuery方法用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象。
2.1、Create(插入操作)
使用executeUpdate(String sql)方法完成数据添加操作,示例操作:
public void testInsert() { // Random random = new Random(); // String id = random.nextInt(100000) + ""; String id = "100"; String name = "wangwu"; String password ="123"; String email = "aaa@163.com"; String birthday = "2016-09-03"; StringBuilder tmp = new StringBuilder(); tmp.append("insert into users(id,name,password,email,birthday)"); tmp.append("values("); tmp.append("‘" + id + "‘ , "); tmp.append("‘" + name + "‘ , "); tmp.append("‘" + password + "‘ , "); tmp.append("‘" + email + "‘ , "); tmp.append("‘" + birthday + "‘ "); tmp.append(")"); String sql = tmp.toString(); System.out.println(sql); Connection conn = getConnection(); Statement st = null; try { st = conn.createStatement(); int num = st.executeUpdate(sql); if (num > 0) { System.out.println("插入成功!!!"); } } catch (SQLException e) { e.printStackTrace(); } finally { if (null != st) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
2.2、Update(修改操作)
使用executeUpdate(String sql)方法完成数据修改操作,示例操作:
public void testUpdate() { Connection conn = getConnection(); Statement st = null; try { st = conn.createStatement(); String sql = "update users set name=‘lisi100‘ where id= 100"; System.out.println(sql); int num = st.executeUpdate(sql); if (num > 0) { System.out.println("修改成功!!!"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (null != st) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
2.3、Delete(删除操作)
使用executeUpdate(String sql)方法完成数据删除操作,示例操作:
public void testDelete() { Connection conn = getConnection(); Statement st = null; try { st = conn.createStatement(); String sql = "delete from users where id= 100"; System.out.println(sql); int num = st.executeUpdate(sql); if (num > 0) { System.out.println("删除成功!!!"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (null != st) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
2.4 Read(读操作)
使用executeQuery(String sql)方法完成数据查询操作,示例操作:
public void testRead() { Connection conn = getConnection(); Statement st = null; ResultSet rs = null; try { st = conn.createStatement(); String sql = "select * from users"; rs = st.executeQuery(sql); String name = null; while (rs.next()) { name = rs.getString("name"); System.out.println("读取到的用户名 name=" + name); } } catch (SQLException e) { e.printStackTrace(); } finally { if (null != rs) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (null != st) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
进一步的优化,释放资源的代码可以抽取出来:
/** * @Method: release * @Description: 释放资源, 要释放的资源包括Connection数据库连接对象,负责执行SQL命令的Statement对象, * 存储查询结果的ResultSet对象 * * @param conn * @param st * @param rs */ public static void release(Connection conn, Statement st, ResultSet rs) { if (rs != null) { try { // 关闭存储查询结果的ResultSet对象 rs.close(); } catch (Exception e) { e.printStackTrace(); } rs = null; } if (st != null) { try { // 关闭负责执行SQL命令的Statement对象 st.close(); } catch (Exception e) { e.printStackTrace(); } } if (conn != null) { try { // 关闭Connection数据库连接对象 conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
3 PreparedStatement
PreperedStatement是Statement的子类,它的实例对象可以通过调用Connection.preparedStatement()方法获得,相对于Statement对象而言:PreperedStatement可以避免SQL注入的问题。
Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。PreparedStatement可对SQL进行预编译,从而提高数据库的执行效率。并且PreperedStatement对于sql中的参数,允许使用占位符的形式进行替换,简化sql语句的编写。
使用PreparedStatement重写CRUD的操作,比较下与Statement的不同。
public void insert() { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { // 获取一个数据库连接 conn = getConnection(); // 要执行的SQL命令,SQL中的参数使用?作为占位符 String sql = "insert into users(id,name,password,email,birthday) values(?,?,?,?,?)"; // 通过conn对象获取负责执行SQL命令的prepareStatement对象 st = conn.prepareStatement(sql); // 为SQL语句中的参数赋值,注意,索引是从1开始的 st.setInt(1, 1);// id是int类型的 st.setString(2, "张三");// name是varchar(字符串类型) st.setString(3, "123");// password是varchar(字符串类型) st.setString(4, "bhsh@sina.com");// email是varchar(字符串类型) st.setDate(5, new java.sql.Date(new Date().getTime()));// birthday是date类型 // 执行插入操作,executeUpdate方法返回成功的条数 int num = st.executeUpdate(); if (num > 0) { System.out.println("插入成功!!"); } } catch (Exception e) { e.printStackTrace(); } finally { // SQL执行完成之后释放相关资源 release(conn, st, rs); } } public void delete() { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { conn = getConnection(); String sql = "delete from users where id=?"; st = conn.prepareStatement(sql); st.setInt(1, 1); int num = st.executeUpdate(); if (num > 0) { System.out.println("删除成功!!"); } } catch (Exception e) { e.printStackTrace(); } finally { release(conn, st, rs); } } public void update() { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { conn = getConnection(); String sql = "update users set name=?,email=? where id=?"; st = conn.prepareStatement(sql); st.setString(1, "王五"); st.setString(2, "wangwu@sina.com"); st.setInt(3, 1); int num = st.executeUpdate(); if (num > 0) { System.out.println("更新成功!!"); } } catch (Exception e) { e.printStackTrace(); } finally { release(conn, st, rs); } } public void find() { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { conn = getConnection(); String sql = "select * from users where id=?"; st = conn.prepareStatement(sql); st.setInt(1, 1); rs = st.executeQuery(); if (rs.next()) { System.out.println(rs.getString("name")); } } catch (Exception e) { } finally { release(conn, st, rs); } }
JavaWeb学习总结-10 JDBC的CRUD