<html>
<head>
<meta charset="utf-8">
<title>title>
head>
<body>
body>
html>
// 1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取链接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_demo", "root", "123");
// 3.获得语句执行者
String sql = "insert into category(cid, name) values('007', '分类')";
Statement stmt = conn.createStatement();
// 预处理
// String sql = "insert into category(cid, name) values(?, ?)";
// PreparedStatement psmt = con.prepareStatement(sql);
// 4.执行sql语句
ResultSet rs = stmt.executeQuery(sql);
// 5.处理结果
// 光标移动到第一行
rs.next();
// 获取第一行第一列的数据
rs.getInt(1);
// 6.释放资源
rs.close();
stmt.close();
conn.close();
分页查询 Limit
Limit 接受一个或两个数字参数。参数必须是一个整数常量。如果给定两个参数,第一个参数指定第一个返回记录行的偏移量,第二个参数指定返回记录行的最大数目。初始记录行的偏移量是 0(而不是 1)
SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15
当调用 close() 方法时不是销毁连接,而是归还连接。
连接池公共接口:javax.sql.DataSource,常见连接池:DBCP、C3P0
public class MyDataSource implements DataSource{
//1.创建1个容器用于存储Connection对象
private static LinkedList<Connection> pool = new LinkedList<Connection>();
//2.创建5个连接放到容器中去
static{
for (int i = 0; i < 5; i++) {
Connection conn = JDBCUtils_V3.getConnection();
pool.add(conn);
}
}
/**
* 重写获取连接的方法
*/
@Override
public Connection getConnection() throws SQLException {
Connection conn = null;
//3.使用前先判断
if(pool.size()==0){
//4.池子里面没有,我们再创建一些
for (int i = 0; i < 5; i++) {
conn = JDBCUtils_V3.getConnection();
pool.add(conn);
}
}
//5.从池子里面获取一个连接对象Connection
conn = pool.remove(0);
return conn;
}
/**
* 归还连接对象到连接池中去
*/
public void backConnection(Connection conn){
pool.add(conn);
}
@Override
……
}
C3P0连接池是开源免费,目前使用它的开源项目有Spring、Hibernate等,使用第三方工具还需要导入jar包,使用时一般还需要配置文件(c3p0-config.xml)
官网说明:https://www.mchange.com/projects/c3p0/
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driverproperty>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/web_test?useSSL=falseproperty>
<property name="user">rootproperty>
<property name="password">123property>
<property name="initialPoolSize">5property>
<property name="maxPoolSize">20property>
default-config>
<named-config name="itheima">
<property name="driverClass">com.mysql.jdbc.Driverproperty>
<property name="jdbcUrl">jdbc:mysql:///web_testproperty>
<property name="user">rootproperty>
<property name="password">123property>
named-config>
c3p0-config>
public class TestC3P0 {
@Test
public void testAddUser() {
Connection conn = null;
PreparedStatement pstmt = null;
// 1.创建自定义连接池对象
ComboPooledDataSource dataSource = new ComboPooledDataSource(); //加载默认配置
// ComboPooledDataSource dataSource = new ComboPooledDataSource("itheima"); //加载有名称的配置
try {
// 2.从池子中获取连接
conn = dataSource.getConnection();
String sql = "insert into tbl_user values(null,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "吕布");
pstmt.setString(2, "貂蝉");
int rows = pstmt.executeUpdate();
if (rows > 0) {
System.out.println("添加成功!");
} else {
System.out.println("添加失败!");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
conn.close();
pstmt.close();
}
}
}
Apache common的一员,企业开发中常见,tomcat的内置连接池
public class DBCPUtils {
private static DataSource dataSource;
static{
try {
//1.加载找properties文件输入流
InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
//2.加载输入流
Properties props = new Properties();
props.load(is);
//3.创建数据源
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public class TestDBCP {
@Test
public void testUpdateUserById(){
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBCPUtils.getConnection();
String sql ="update tbl_user set upassword=? where uid=?";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, "李四");
pstmt.setInt(2, 2);
int rows = pstmt.executeUpdate();
if(rows>0){
System.out.println("更新成功!");
}else{
System.out.println("更新失败!");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
对于增删改查等有较多相同代码,只有少部分不同代码处理 → 不同代码处用传参解决
public class User {
private int uid;
private String uname;
private String upassword;
public User() {
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpassword() {
return upassword;
}
public void setUpassword(String upassword) {
this.upassword = upassword;
}
}
public class TestDBUtils1 {
// 增删改测试用例
@Test
public void testAddUser() {
try {
// 1.创建核心类QueryRunner
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "insert into tbl_user values(null,?,?)";
// 3.为站位符设置值
Object[] params = { "余淮", "耿耿" };
// 4.执行添加操作
int rows = qr.update(sql, params);
if (rows > 0) {
System.out.println("添加成功!");
} else {
System.out.println("添加失败!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//查测试用例
@Test
public void testQueryAll() {
try {
// 1.获取核心类queryRunner
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写sql语句
String sql = "select * from tbl_user";
// 3.执行查询操作
List<User> users = qr.query(sql, new BeanListHandler<User>(User.class));
// 4.对结果集集合进行遍历
for (User user : users) {
System.out.println(user.getUname() + " : " + user.getUpassword());
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}