JDBC 学习笔记
Posted 笑虾
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBC 学习笔记相关的知识,希望对你有一定的参考价值。
JDBC 学习笔记
带参数查询
demo 所以完全没有处理异常。
package com.jerry.utilsdemo;
import java.sql.*;
public class mysqlDemo {
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) throws Exception {
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 带参查询
PreparedStatement pstmt = conn.prepareStatement("SELECT title, content, author FROM poem where title = ?");
pstmt.setString(1, "痴情癫");
ResultSet rs = pstmt.executeQuery();
// 展开结果
while(rs.next()){
System.out.println("title : " + rs.getString("title"));
System.out.println("content : " + rs.getString("content"));
System.out.println("author : " + rs.getString("author"));
}
// 释放资源
rs.close();
pstmt.close();
conn.close();
}
}
工具 commons-dbutils
- pom.xml
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
- DBUtilsDemo.java
package com.jerry.utilsdemo;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtilsDemo {
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) throws Exception {
Connection conn = null;
QueryRunner queryRunner = new QueryRunner();
//1: 注册 JDBC 驱动
DbUtils.loadDriver(JDBC_DRIVER);
//2: 打开连接
System.out.println("连接到数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//3: 创建返回集
ResultSetHandler<Poem> resultHandler = new BeanHandler<Poem>(Poem.class);
try {
String sql = "SELECT title, content, author FROM poem WHERE title = ?";
Poem poem = queryRunner.query(conn, sql, resultHandler, "爱云说");
System.out.println(poem);
} finally {
DbUtils.close(conn);
}
}
}
参考资料
以上是关于JDBC 学习笔记的主要内容,如果未能解决你的问题,请参考以下文章
JDBC学习笔记——利用反射及JDBC元数据编写通用的查询方法
[原创]java WEB学习笔记61:Struts2学习之路--通用标签 property,uri,param,set,push,if-else,itertor,sort,date,a标签等(代码片段