JSP基础(十四)——使用JDBC的Statement对象和PreparedStatement对象对数据库进行CRUD

来源:互联网 发布:java动态bean 编辑:程序博客网 时间:2024/06/07 00:14

一、Statement对象简介

    JDBC 中的Statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。

    Statement对象的executeUpdate方法,用于向数据库发送增、删、改的SQL语句,executeUpdate执行完后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)。

     Statement.executeQuery方法用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象。

1、CRUD操作——create

   使用executeUpdate(String sql)方法完成数据添加操作(插入:insert into table1(field1,field2) values(value1,value2)),示例操作

Statement st = conn.createStatement();String sql = "update user set name='' where name='' ";int num = st.executeUpdate(sql);if(num>0) {    System.out.println("插入成功!!!");}


2、CRUD操作——update

使用executeUpdate(String sql)方法完成数据修改操作(更新:update table1 set field1=value1 where 范围),示例操作

Statement st = conn.createStatement();String sql = "update user set name='' where name=''";int num = st.executeUpdate(sql);if(num>0) {System.out.println("更新成功!!!");}

3、CRUD操作——delete

使用executeUpdate(String sql)方法完成数据库删除操作(删除:delete from table1 where 范围),示例操作:

Statement st = conn.createStatement();String sql = "delete from user where id=1";int num = st.executeUpdate(sql);if(num>0) {System.out.println("删除成功!!!");}    


4、CRUD操作——read

使用executeUpdate(String sql)方法完成数据查询操作(查询:select * from table1 where 范围 ),示例操作:

Statement st = conn.createStatement();String sql = "select * from user where id=1";ResultSet rs = st.executeUpdate(sql);while(rs.next()) {//根据获取列的数据类型,分别调用rs的相应方法映射到Java对象中}


二、使用JDBC对数据库进行增删改查

2.1 搭建实验环境

    1.在我的上一篇博客中(点击打开)搭建的实验环境基础之上,在src下创建一个db.properties文件,如下图:



    2.编写一个JdbcUtils工具类,用于连接数据库,获取数据库连接和释放数据库连接,代码如下:

package me.zl.utils;import java.io.IOException;import java.io.InputStream;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;import com.mysql.jdbc.Connection;public class JdbcUtils {private static String driver = null;private static String url = null;private static String username = null;private static String password = null;static {try {//读取db.properties文件中的数据库连接信息InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");Properties prop = new Properties();prop.load(in);//获取数据库连接驱动driver = prop.getProperty("driver");//获取数据库连接URL地址url = prop.getProperty("url");//获取数据库连接用户名username = prop.getProperty("username");//获取数据库连接密码password = prop.getProperty("password");//加载数据库驱动Class.forName(driver);} catch (Exception e) {throw new ExceptionInInitializerError(e);}}/** * @Metod:getConnection * @Description:获取数据库连接对象 * @return Connection数据库连接对象 * @throws SQLException */public static Connection getConnection() throws SQLException{return (Connection) DriverManager.getConnection(url,username,password);}/** * @Method:release * @Description:释放资源,1.要释放的资源包括Connection数据库连接对象,2.负责执行SQL命令的Statement对象,3.存储查询结果集的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();}}if(st != null) {try {//关闭负责执行SQL命令的Statement对象st.close();} catch (SQLException e) {e.printStackTrace();}}if(conn != null) {try {//关闭Connection数据库连接对象conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}//public static void main(String[] args) {//// TODO Auto-generated method stub////}}

2.2 使用Statement对象完成对数据库的CRUD操作

测试代码如下:

package me.zl.demo;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import me.zl.utils.JdbcUtils;/** * @ClassName:JdbcCRUDByStatement * @Description:通过Statement对象完成对数据库的CRUD操作 */public class JdbcCRUDByStatement {public void insert() {Connection conn = null;Statement st = null;ResultSet rs = null;try {//获取一个数据库连接conn = JdbcUtils.getConnection();//通过conn对象获取负责执行SQL命令的Statement对象st = conn.createStatement();//要执行的SQL命令String sql = "insert into users(id,name,password,email,birthday) values(4,'xiaozhou','123','zl@qq.com','1996-10-05')";//执行插入操作,executeUpdate方法返回成功条数int num = st.executeUpdate(sql);if(num>0) {System.out.println("插入成功!!!");}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {//SQL执行完成之后释放相关资源JdbcUtils.release(conn, st, rs);}}public void delete() {Connection conn = null;Statement st = null;ResultSet rs = null;try {conn = JdbcUtils.getConnection();String sql = "delete from users where id=3";st = conn.createStatement();int num = st.executeUpdate(sql);if(num>0) {System.out.println("删除成功!!!");}} catch (SQLException e) {e.printStackTrace();} finally {JdbcUtils.release(conn, st, rs);}}public void update() {Connection conn = null;Statement st = null;ResultSet rs = null;try {conn = JdbcUtils.getConnection();String sql = "update users set name='Miss Zhou',email='zhou@qq.com' where id=4";st = conn.createStatement();int num = st.executeUpdate(sql);if(num>0) {System.out.println("更新成功!!!");}} catch (SQLException e) {e.printStackTrace();} finally {JdbcUtils.release(conn, st, rs);}}public static void find() {Connection conn = null;Statement st = null;ResultSet rs = null;try {conn = JdbcUtils.getConnection();String sql = "select * from users where id=4";st = conn.createStatement();rs = st.executeQuery(sql);if(rs.next()) {System.out.println(rs.getString("name"));}} catch (SQLException e) {e.printStackTrace();} finally {JdbcUtils.release(conn, st, rs);}}//public static void main(String[] args) {//    //}}

三、PreparedStatement对象简介

    PreparedStatement是Statement的子类,它的实例对象可以通过调用Connection.preparedStatement()方法获得,相对于Statement对象而言:PreparedStatement可以避免SQL注入的问题。

    Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。PreparedStatement可对SQL进行预编译,从而提高数据库的执行效率,并且PreparedStatement对于sql中的参数,允许使用占位符的形式进行替换,简化SQL语句的编写。

3.1 使用PreparedStatement对象完成对数据库的CRUD操作

测试代码如下:

package me.zl.demo;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Date;import me.zl.utils.JdbcUtils;/** * @ClassName:JdbcCRUDByPreparedStatement * @Description:通过PreparedStatement对象完成对数据库的CRUD操作 */public class JdbcCRUDByPreparedStatement {public void insert() {Connection conn = null;PreparedStatement st = null;ResultSet rs = null;try {// 获取一个数据库连接conn = JdbcUtils.getConnection();// 要执行的SQL命令,SQL中的参数使用?作为占位符String sql = "insert into users(id,name,password,email,birthday) values(?,?,?,?,?)";// 通过conn对象获取负责执行SQL命令的PreparedStatement对象st = conn.prepareStatement(sql); /**               * SQL语句中各个字段的类型如下:                *  +----------+-------------+                | Field    | Type   |                +----------+-------------+                | id    | int(11)   |                | name   | varchar(40) |                | password | varchar(40) |                | email   | varchar(60) |                | birthday | date     |                +----------+-------------+               */st.setInt(1, 1);// id是int类型st.setString(2, "xiaoxiao");st.setString(3, "1234567");st.setString(4, "xx@qq.com");st.setDate(5, new java.sql.Date(new Date().getTime()));// 执行插入操作,executeUpdate()方法返回成功的条数int num = st.executeUpdate();if (num > 0) {System.out.println("插入成功!!!");}} catch (SQLException e) {e.printStackTrace();} finally {// 执行SQL完成之后释放相关资源JdbcUtils.release(conn, st, rs);}}public void delete() {Connection conn = null;PreparedStatement st = null;ResultSet rs = null;try {conn = JdbcUtils.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 (SQLException e) {e.printStackTrace();}JdbcUtils.release(conn, st, rs);}public void update() {Connection conn = null;PreparedStatement st = null;ResultSet rs = null;try {conn = JdbcUtils.getConnection();String sql = "update users set name=?,email=? where id=?";st = conn.prepareStatement(sql);st.setString(1, "xiaoda");st.setString(2, "xiaoda@sina.com");st.setInt(3, 4);int num = st.executeUpdate();if (num > 0) {System.out.println("更新成功!!!");}} catch (SQLException e) {e.printStackTrace();} finally {JdbcUtils.release(conn, st, rs);}}public void find() {Connection conn = null;PreparedStatement st = null;ResultSet rs = null;try {conn = JdbcUtils.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 {JdbcUtils.release(conn, st, rs);}}// public static void main(String[] args) {//// }}




阅读全文
0 0
原创粉丝点击