javaweb学习总结(三十三)——使用JDBC对数据库进行CRUD

javaweb学习总结(三十三)——使用JDBC对数据库进行CRUD

一、statement对象介绍  

  Jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。
  Statement对象的executeUpdate方法,用于向数据库发送增、删、改的sql语句,executeUpdate执行完后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)。
  Statement.executeQuery方法用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象。

1.1、CRUD操作-create

  使用executeUpdate(String sql)方法完成数据添加操作,示例操作:

1 Statement st = conn.createStatement();

2 String sql = "insert into user(….) values(…..) "; 

3 int num = st.executeUpdate(sql);

4 if(num>0){

5     System.out.println("插入成功!!!");

6 }

1.2、CRUD操作-update

  使用executeUpdate(String sql)方法完成数据修改操作,示例操作:

1 Statement st = conn.createStatement();

2 String sql = “update user set name=‘’ where name=‘’"; 

3 int num = st.executeUpdate(sql);

4 if(num>0){

5     System.out.println(“修改成功!!!");

6 }

1.3、CRUD操作-delete

  使用executeUpdate(String sql)方法完成数据删除操作,示例操作:

1 Statement st = conn.createStatement();

2 String sql = “delete from user where id=1; 

3 int num = st.executeUpdate(sql);

4 if(num>0){

5     System.out.println(“删除成功!!!");

6 }

1.4、CRUD操作-read

  使用executeQuery(String sql)方法完成数据查询操作,示例操作:

1 Statement st = conn.createStatement();

2 String sql = “select * from user where id=1; 

3 ResultSet rs = st.executeUpdate(sql);

4 while(rs.next()){

5     //根据获取列的数据类型,分别调用rs的相应方法映射到java对象中

6 }

二、使用jdbc对数据库增删改查

2.1、搭建实验环境    

  1、在mysql中创建一个库,并创建user表和插入表的数据。

  SQL脚本如下:

复制代码
 1 create database jdbcStudy;

 2 

 3 use jdbcStudy;

 4 

 5 create table users(

 6     id int primary key,

 7     name varchar(40),

 8     password varchar(40),

 9     email varchar(60),

10     birthday date

11 );
复制代码

  2、新建一个JavaWeb工程,并导入MySQL数据库驱动。

  javaweb学习总结(三十三)——使用JDBC对数据库进行CRUD

  3、在src目录下创建一个db.properties文件,如下图所示:

  

  在db.properties中编写MySQL数据库的连接信息,代码如下所示:

1 driver=com.mysql.jdbc.Driver

2 url=jdbc:mysql://localhost:3306/jdbcStudy

3 username=root

4 password=XDP

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

复制代码
 1 package me.gacl.utils;

 2 

 3 import java.io.InputStream;

 4 import java.sql.Connection;

 5 import java.sql.DriverManager;

 6 import java.sql.ResultSet;

 7 import java.sql.SQLException;

 8 import java.sql.Statement;

 9 import java.util.Properties;

10 

11 public class JdbcUtils {

12 

13     private static String driver = null;

14     private static String url = null;

15     private static String username = null;

16     private static String password = null;

17     

18     static{

19         try{

20             //读取db.properties文件中的数据库连接信息

21             InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");

22             Properties prop = new Properties();

23             prop.load(in);

24             

25             //获取数据库连接驱动

26             driver = prop.getProperty("driver");

27             //获取数据库连接URL地址

28             url = prop.getProperty("url");

29             //获取数据库连接用户名

30             username = prop.getProperty("username");

31             //获取数据库连接密码

32             password = prop.getProperty("password");

33             

34             //加载数据库驱动

35             Class.forName(driver);

36             

37         }catch (Exception e) {

38             throw new ExceptionInInitializerError(e);

39         }

40     }

41     

42     /**

43     * @Method: getConnection

44     * @Description: 获取数据库连接对象

45     * @Anthor:孤傲苍狼

46     *

47     * @return Connection数据库连接对象

48     * @throws SQLException

49     */ 

50     public static Connection getConnection() throws SQLException{

51         return DriverManager.getConnection(url, username,password);

52     }

53     

54     /**

55     * @Method: release

56     * @Description: 释放资源,

57     *     要释放的资源包括Connection数据库连接对象,负责执行SQL命令的Statement对象,存储查询结果的ResultSet对象

58     * @Anthor:孤傲苍狼

59     *

60     * @param conn

61     * @param st

62     * @param rs

63     */ 

64     public static void release(Connection conn,Statement st,ResultSet rs){

65         if(rs!=null){

66             try{

67                 //关闭存储查询结果的ResultSet对象

68                 rs.close();

69             }catch (Exception e) {

70                 e.printStackTrace();

71             }

72             rs = null;

73         }

74         if(st!=null){

75             try{

76                 //关闭负责执行SQL命令的Statement对象

77                 st.close();

78             }catch (Exception e) {

79                 e.printStackTrace();

80             }

81         }

82         

83         if(conn!=null){

84             try{

85                 //关闭Connection数据库连接对象

86                 conn.close();

87             }catch (Exception e) {

88                 e.printStackTrace();

89             }

90         }

91     }

92 }
复制代码

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

  测试代码如下:

复制代码
  1 package me.gacl.demo;

  2 

  3 import java.sql.Connection;

  4 import java.sql.ResultSet;

  5 import java.sql.Statement;

  6 import me.gacl.utils.JdbcUtils;

  7 

  8 import org.junit.Test;

  9 

 10 /**

 11 * @ClassName: JdbcCRUDByStatement

 12 * @Description: 通过Statement对象完成对数据库的CRUD操作

 13 * @author: 孤傲苍狼

 14 * @date: 2014-9-15 下午11:22:12

 15 *

 16 */ 

 17 public class JdbcCRUDByStatement {

 18 

 19     @Test

 20     public void insert(){

 21         Connection conn = null;

 22         Statement st = null;

 23         ResultSet rs = null;

 24         try{

 25             //获取一个数据库连接

 26             conn = JdbcUtils.getConnection();

 27             //通过conn对象获取负责执行SQL命令的Statement对象

 28             st = conn.createStatement();

 29             //要执行的SQL命令

 30             String sql = "insert into users(id,name,password,email,birthday) values(3,'白虎神皇','123','[email protected]','1980-09-09')";

 31             //执行插入操作,executeUpdate方法返回成功的条数

 32             int num = st.executeUpdate(sql);

 33             if(num>0){

 34                 System.out.println("插入成功!!");

 35             }

 36             

 37         }catch (Exception e) {

 38             e.printStackTrace();

 39         }finally{

 40             //SQL执行完成之后释放相关资源

 41             JdbcUtils.release(conn, st, rs);

 42         }

 43     }

 44     

 45     @Test

 46     public void delete(){

 47         Connection conn = null;

 48         Statement st = null;

 49         ResultSet rs = null;

 50         try{

 51             conn = JdbcUtils.getConnection();

 52             String sql = "delete from users where id=3";

 53             st = conn.createStatement();

 54             int num = st.executeUpdate(sql);

 55             if(num>0){

 56                 System.out.println("删除成功!!");

 57             }

 58         }catch (Exception e) {

 59             e.printStackTrace();

 60             

 61         }finally{

 62             JdbcUtils.release(conn, st, rs);

 63         }

 64     }

 65     

 66     @Test

 67     public void update(){

 68         Connection conn = null;

 69         Statement st = null;

 70         ResultSet rs = null;

 71         try{

 72             conn = JdbcUtils.getConnection();

 73             String sql = "update users set name='孤傲苍狼',email='[email protected]' where id=3";

 74             st = conn.createStatement();

 75             int num = st.executeUpdate(sql);

 76             if(num>0){

 77                 System.out.println("更新成功!!");

 78             }

 79         }catch (Exception e) {

 80             e.printStackTrace();

 81             

 82         }finally{

 83             JdbcUtils.release(conn, st, rs);

 84         }

 85     }

 86     

 87     @Test

 88     public void find(){

 89         Connection conn = null;

 90         Statement st = null;

 91         ResultSet rs = null;

 92         try{

 93             conn = JdbcUtils.getConnection();

 94             String sql = "select * from users where id=3";

 95             st = conn.createStatement();

 96             rs = st.executeQuery(sql);

 97             if(rs.next()){

 98                 System.out.println(rs.getString("name"));

 99             }

100         }catch (Exception e) {

101             e.printStackTrace();

102         }finally{

103             JdbcUtils.release(conn, st, rs);

104         }

105     }

106 }
复制代码

三、PreparedStatement对象介绍

  PreperedStatement是Statement的子类,它的实例对象可以通过调用Connection.preparedStatement()方法获得,相对于Statement对象而言:PreperedStatement可以避免SQL注入的问题。
  Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。PreparedStatement可对SQL进行预编译,从而提高数据库的执行效率。并且PreperedStatement对于sql中的参数,允许使用占位符的形式进行替换,简化sql语句的编写。

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

  测试代码如下:

复制代码
  1 package me.gacl.demo;

  2 

  3 import java.sql.Connection;

  4 import java.sql.PreparedStatement;

  5 import java.sql.ResultSet;

  6 import java.util.Date;

  7 import me.gacl.utils.JdbcUtils;

  8 import org.junit.Test;

  9 

 10 /**

 11 * @ClassName: JdbcCRUDByPreparedStatement

 12 * @Description: 通过PreparedStatement对象完成对数据库的CRUD操作

 13 * @author: 孤傲苍狼

 14 * @date: 2014-9-15 下午11:21:42

 15 *

 16 */ 

 17 public class JdbcCRUDByPreparedStatement {

 18 

 19     @Test

 20     public void insert(){

 21         Connection conn = null;

 22         PreparedStatement st = null;

 23         ResultSet rs = null;

 24         try{

 25             //获取一个数据库连接

 26             conn = JdbcUtils.getConnection();

 27             //要执行的SQL命令,SQL中的参数使用?作为占位符

 28             String sql = "insert into users(id,name,password,email,birthday) values(?,?,?,?,?)";

 29             //通过conn对象获取负责执行SQL命令的prepareStatement对象

 30             st = conn.prepareStatement(sql);

 31             //为SQL语句中的参数赋值,注意,索引是从1开始的

 32             /**

 33              * SQL语句中各个字段的类型如下:

 34              *  +----------+-------------+

 35                 | Field    | Type        |

 36                 +----------+-------------+

 37                 | id       | int(11)     |

 38                 | name     | varchar(40) |

 39                 | password | varchar(40) |

 40                 | email    | varchar(60) |

 41                 | birthday | date        |

 42                 +----------+-------------+

 43              */

 44             st.setInt(1, 1);//id是int类型的

 45             st.setString(2, "白虎神皇");//name是varchar(字符串类型)

 46             st.setString(3, "123");//password是varchar(字符串类型)

 47             st.setString(4, "[email protected]");//email是varchar(字符串类型)

 48             st.setDate(5, new java.sql.Date(new Date().getTime()));//birthday是date类型

 49             //执行插入操作,executeUpdate方法返回成功的条数

 50             int num = st.executeUpdate();

 51             if(num>0){

 52                 System.out.println("插入成功!!");

 53             }

 54             

 55         }catch (Exception e) {

 56             e.printStackTrace();

 57         }finally{

 58             //SQL执行完成之后释放相关资源

 59             JdbcUtils.release(conn, st, rs);

 60         }

 61     }

 62     

 63     @Test

 64     public void delete(){

 65         Connection conn = null;

 66         PreparedStatement st = null;

 67         ResultSet rs = null;

 68         try{

 69             conn = JdbcUtils.getConnection();

 70             String sql = "delete from users where id=?";

 71             st = conn.prepareStatement(sql);

 72             st.setInt(1, 1);

 73             int num = st.executeUpdate();

 74             if(num>0){

 75                 System.out.println("删除成功!!");

 76             }

 77         }catch (Exception e) {

 78             e.printStackTrace();

 79         }finally{

 80             JdbcUtils.release(conn, st, rs);

 81         }

 82     }

 83     

 84     @Test

 85     public void update(){

 86         Connection conn = null;

 87         PreparedStatement st = null;

 88         ResultSet rs = null;

 89         try{

 90             conn = JdbcUtils.getConnection();

 91             String sql = "update users set name=?,email=? where id=?";

 92             st = conn.prepareStatement(sql);

 93             st.setString(1, "gacl");

 94             st.setString(2, "[email protected]");

 95             st.setInt(3, 2);

 96             int num = st.executeUpdate();

 97             if(num>0){

 98                 System.out.println("更新成功!!");

 99             }

100         }catch (Exception e) {

101             e.printStackTrace();

102             

103         }finally{

104             JdbcUtils.release(conn, st, rs);

105         }

106     }

107     

108     @Test

109     public void find(){

110         Connection conn = null;

111         PreparedStatement st = null;

112         ResultSet rs = null;

113         try{

114             conn = JdbcUtils.getConnection();

115             String sql = "select * from users where id=?";

116             st = conn.prepareStatement(sql);

117             st.setInt(1, 1);

118             rs = st.executeQuery();

119             if(rs.next()){

120                 System.out.println(rs.getString("name"));

121             }

122         }catch (Exception e) {

123             

124         }finally{

125             JdbcUtils.release(conn, st, rs);

126         }

127     }

128 }
复制代码

   以上就是使用JDBC对数据库进行CRUD的简单总结。

你可能感兴趣的:(javaweb)