【Java工具、MySQL数据库】JDBC&DBUtils使用

mac2022-06-30  22

JDBC使用

以下代码均未捕获异常

一、JDBC处理SQL语句

1)Statment:执行完整SQL命令

拼接麻烦,可读性差(建议在只使用一次的情况下使用,也可以通过字符串的合并来实现PreparedStatment的操作,但是其没有预编译的过程,所以多次使用这个方法,时间效率较低)

Connection conn = null; //加载驱动 Class.forName("com.mysql.jdbc.Driver"); //建立连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF8","root","password"); //发送SQL语句 Statement st = conn.createStatement(); int result=st.executeUpdate("INSERT INTO admin VALUES ('A2A','BBBBBB')");

2)PreparedStatment:执行带参数的SQL 命令

安全性高,可读性好,预编译(多次使用时会直接使用编译好的SQL语句),性能更好,可预防SQL注入的情况。

Connection conn = null; //加载驱动 Class.forName("com.mysql.jdbc.Driver"); //建立连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF8","root","password"); //创建sql语句 PreparedStatement pre = conn.prepareStatement("select * from admin where name = ? and password = ?"); //给参数赋值 pre.setString(1,"name"); pre.setString(2,"password"); //发送sql语句,并获取sql语句返回集合 ResultSet rs = pre.executeQuery(); Admin admin = null; while(rs.next()){ admin = new Admin(); admin.setName(rs.getString("name")); admin.setName(rs.getString("password")); } //全关,释放资源,可放在finally{}里面 pre.close(); rs.close(); conn.close();

二、实现增删改

Connection conn = null; //加载驱动 Class.forName("com.mysql.jdbc.Driver"); //建立连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF8","root","password"); //发送SQL语句 Statement st = conn.createStatement(); //insert/update/delete/select /返回1则代表数据库操作成功 int result=st.executeUpdate("INSERT INTO admin VALUES ('A2A','BBBBBB')"); //全关,释放资源,可放在finally{}里面 st.close(); conn.close();

三、实现查(用ResultSet获取结果集)

Connection conn = null; //加载驱动 Class.forName("com.mysql.jdbc.Driver"); //建立连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF8","root","password"); Statement st = conn.createStatement(); //查询结果集 ResultSet rs = stat.executeQuery("select * from admin"); //创建一个集合来存储查询到的值,如果只有一个则没有这个必要 List<Admin> admins = new ArrayList<>(); while (rs.next()){ //每次循环的rs:结果集的一行 String name= rs.getString("name"); String passowrd= rs.getString("password"); Admin admin = Admin(name,password); admins.add(admin); } //全关,释放资源,可放在finally{}里面 st.close(); rs.close(); conn.close();

四、JDBC资源释放

//全关,释放资源,可放在finally{}里面 st.close(); rs.close(); conn.close();

五、JDBC小结

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uJUlToWR-1570172241634)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1558849968963.png)]

C3P0连接池配置

//在src,java类的主目录下,新建一个c3p0-config.xml <c3p0-config> <!-- 默认配置,如果没有指定则使用这个配置 --> <default-config> <!-- 基本配置:填写数据库名、登陆账号密码 --> <property name="driverClass">com.mysql.jdbc.Driver</property> <!-- 此处回环地址后的/填写数据库名 --> <property name="jdbcUrl">jdbc:mysql://localhost:3306/tangxz</property> <property name="user">root</property> <property name="password">5516</property> <!--扩展配置--> <property name="checkoutTimeout">30000</property> <property name="idleConnectionTestPeriod">30</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> <!-- 命名的配置 --> <named-config name="c3p0"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/tangxz</property> <property name="useSSL">false</property> <property name="user">root</property> <property name="password">5516</property> <!-- 如果池中数据连接不够时一次增长多少个 --> <property name="acquireIncrement">5</property> <property name="initialPoolSize">20</property> <property name="minPoolSize">10</property> <property name="maxPoolSize">40</property> <property name="maxStatements">20</property> <property name="maxStatementsPerConnection">5</property> </named-config> </c3p0-config> //在一个类中,导入上面配置的连接池信息 //创建一个c3p0连接池 static ComboPooledDataSource ds= new ComboPooledDataSource(); //返回一个c3p0连接池中的连接 public static Connection getConnection() throws SQLException { return ds.getConnection(); }

DBUtils使用c3p0

一、DBUtils下载地址:

http://commons.apache.org/proper/commons-dbutils/download_dbutils.cgi

二、DBUtils简介

1.对于数据表的读操作,他可以把结果转换成List,Array,Set等java集合,便于程序员操作;

2.对于数据表的写操作,也变得很简单(只需写sql语句)

主要方法:

DbUtils类:启动类

ResultSetHandler接口:转换类型接口

MapListHandler类:实现类,把记录转化成List

BeanListHandler类:实现类,把记录转化成List,使记录为JavaBean类型的对象

Query Runner类:执行SQL语句的类

三、实现DBUtils的QreryRunner类:

//dao层通过这句话获取连接池 QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());

QreryRunner类(org.apache.commons.dbutils.QueryRunner) 是Dbutils的核心类之一,它显著的简化了SQL查询,并与ResultSetHandler协同工作将使编码量大为减少。它包含以下几个方法:

query(Connection conn, String sql, Object[] params, ResultSetHandler rsh):执行选择查询,在查询中,对象阵列的值被用来作为查询的置换参数。query(String sql, Object[] params, ResultSetHandler rsh):方法本身不提供数据库连接,执行选择查询,在查询中,对象阵列的值被用来作为查询的置换参数。query(Connection conn, String sql, ResultSetHandler rsh):执行无需参数的选择查询。update(Connection conn, String sql, Object[] params):被用来执行插入、更新或删除(DML)操作。

四、增删改查的实现

1、增

public void insert() throws SQLException { String sql = "insert into admin(name,password) values(?,?)"; String name = "aaaa"; String password = "zzzz"; qr.update(sql, name, password); }

2、删

public void delById(String name) throws SQLException { String sql = "delete from users where name = ?"; qr.update(sql, name); }

3、改

public void update(String name, user user) throws SQLException { String sql = "update users set name=? , password=? where name=?"; qr.update(sql,user.getName(),user.getPassword(),name); }

4、查

//查一个 public user findById(String name) throws SQLException { String sql = "select * from admin where name = ?"; return qr.query(sql, new BeanHandler<>(user.class),name); } //查多个 public List<user> findAll() throws SQLException { String sql = "select * from users"; List<user> user = qr.query(sql, new BeanListHandler<user>(user.class)); return user; }
最新回复(0)