JDBC学习(十一):使用QueryRunner实现update操作

无论是删除、修改和插入,都仅仅是sql语句不同

可以看出,使用数据库连接池,代码量已经很少了,比前面的源代码要简洁得多。(JDBCUtils类在前面的博客中有介绍)

package demo07;

import java.sql.Connection;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.jupiter.api.Test;

import utils.JDBCUtils;

public class DbutilsTest {

	
	/***
	 * 
	 * 测试插入
	 */
	@Test
	public void test1(){
		
		Connection conn = null;
		try {
			QueryRunner runner = new QueryRunner();
			conn = JDBCUtils.getConnectionDruid();
			
			String sql = "insert into beauty (name,sex,borndate,phone)values(?,?,?,?)";
			int insertCount = runner.update(conn, sql, "刘亦菲", "女", "1987-01-01 00:00:00", 123456789);
			System.out.println("添加了"+insertCount+"条记录");
		}  catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.closeResourse(conn, null);
			
		}
		
	}
	
	/***
	 * 
	 * 测试删除
	 */
	@Test
	public void test2(){
		
		Connection conn = null;
		try {
			conn = JDBCUtils.getConnectionDruid();
			QueryRunner runner = new QueryRunner();
			String sql = "delete from beauty where id=?";
			int deleteCount = runner.update(conn, sql, 16);
			System.out.println(deleteCount);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.closeResourse(conn, null);
			
		}		
	}
	
	@Test
	public void test3() {

		Connection conn = null;
		try {
			conn = JDBCUtils.getConnectionDruid();
			QueryRunner runner = new QueryRunner();
			String sql = "update beauty set name=? where id = ?";
			int updateCount = runner.update(conn, sql, "小龙女", 13);
			System.out.println(updateCount);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		JDBCUtils.closeResourse(conn, null);
		
	}
	
}

你可能感兴趣的:(java,java,jar,数据库,jdbc)