JDBC的操作步骤
不同的数据库厂商针对不同的语言提供不同的驱动包 java语言- 连接数据库
驱动jar包-- 核心类( sun公司提供的一套接口规范)
JDBC操作步骤:
1 ) 导入jar包 mysql驱动jar包 mysql- connector- java- 5.1 .37 - bin. jar
2 ) 注册驱动
Class. forName ( "com.mysql.jdbc.Driver" ) ;
3 ) 获取数据库的连接对象
DriverManager. getConnnecton ( String url, String user, String password) -- -- - > Connection
url: 统一资源定位符: jdbc: mysql: / / 127.0 .0 . 1 ( localhost) : 3306 / 数据库名称
user: 用户名
password: 用户密码
4 ) 准备sql语句
DDL, DML. . . .
String sql = "update 表名 set 字段= 值 where 字段 = 值" ;
5 ) 通过连接对象获取执行对象
Connection
createStatement ( ) -- -- > Statement : 执行对象 java. sql. Statement
6 ) 执行更新
Statement: 通用方法
int executeUpdate ( String sql) -- -- - 针对DDL语句: 返回值0
针对DML语句: 操作表的记录 返回值: 行的计数
7 ) 释放资源
释放执行对象
释放连接对象
例:
Class. forName ( "com.mysql.jdbc.Driver" ) ;
Connection conn = DriverManager. getConnection (
"jdbc:mysql://localhost:3306/mydb_05" , "root" , "123456" ) ;
String sql = "update account set balance = balance + 500 where id = 1" ;
Statement stmt = conn. createStatement ( ) ;
int count = stmt. executeUpdate ( sql) ;
System. out. println ( "影响了" + count+ "行" ) ;
stmt. close ( ) ;
conn. close ( ) ;
原生JDBC的增删改查操作
操作DML语句增删改
private static Connection conn;
private static Statement stmt;
try {
Class. forName ( "com.mysql.jdbc.Driver" ) ;
conn = DriverManager. getConnection (
"jdbc:mysql://localhost:3306/mydb_05" , "root" , "123456" ) ;
String sql = "create table student("
+ "id int primary key auto_increment,"
+ "name varchar(10),"
+ "age int,"
+ "gender varchar(2),"
+ "address varchar(20)"
+ ");" ;
stmt = conn. createStatement ( ) ;
int count = stmt. executeUpdate ( sql) ;
System. out. println ( count) ;
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
} finally {
if ( stmt!= null) {
try {
stmt. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
if ( conn!= null) {
try {
conn. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
}
操作DQL语句查询
Connection conn = null ;
Statement stmt = null ;
ResultSet rs = null ;
try {
Class. forName ( "com.mysql.jdbc.Driver" ) ;
conn = DriverManager. getConnection (
"jdbc:mysql://localhost:3306/mydb_05" ,
"root" ,
"123456" ) ;
String sql = "select * from student" ;
stmt = conn. createStatement ( ) ;
rs = stmt. executeQuery ( sql) ;
while ( rs. next ( ) ) {
int id = rs. getInt ( 1 ) ;
String name = rs. getString ( 2 ) ;
int age = rs. getInt ( 3 ) ;
String gender = rs. getString ( 4 ) ;
String address = rs. getString ( 5 ) ;
System. out. println ( id+ "\t" + name+ "\t" + age+ "\t" + gender+ "\t" + address) ;
}
while ( rs. next ( ) ) {
int id = rs. getInt ( "id" ) ;
String name = rs. getString ( "name" ) ;
int age = rs. getInt ( "age" ) ;
String gender = rs. getString ( "gender" ) ;
String address = rs. getString ( "address" ) ;
System. out. println ( id+ "\t" + name+ "\t" + age+ "\t" + gender+ "\t" + address) ;
}
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
} finally {
if ( rs!= null) {
try {
rs. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
if ( stmt!= null) {
try {
stmt. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
if ( conn!= null) {
try {
conn. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
}
原生Jdbc工具类进行封装
手动jdbc工具类的封装: 针对原生Jdbc的封装
例:
public class JdbcUtils {
public static String url = null ;
public static String user = null ;
public static String password = null ;
public static String driverClass = null ;
static {
try {
Properties prop = new Properties ( ) ;
InputStream inputStream = JdbcUtils. class . getClassLoader ( ) . getResourceAsStream ( "jdbc.properties" ) ;
prop. load ( inputStream) ;
System. out. println ( prop) ;
url = prop. getProperty ( "url" ) ;
user = prop. getProperty ( "user" ) ;
password = prop. getProperty ( "password" ) ;
driverClass = prop. getProperty ( "driverClass" ) ;
Class. forName ( driverClass) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
}
}
private JdbcUtils ( ) { }
public static Connection getConnection ( ) {
try {
Connection conn = DriverManager. getConnection ( url, user, password) ;
return conn ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
return null ;
}
public static void close ( ResultSet rs, Statement stmt, Connection conn) {
if ( rs!= null) {
try {
rs. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
if ( stmt!= null) {
try {
stmt. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
if ( conn!= null) {
try {
conn. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
}
public static void close ( Statement stmt, Connection conn) {
close ( null, stmt, conn) ;
}
public static void main ( String[ ] args) {
Connection conn = JdbcUtils. getConnection ( ) ;
System. out. println ( conn) ;
}
}
封装后的Jdbc工具类实现增删查改
加入封装好的jdbc工具类针对DML语句增删改
DQL 查询
例:
Connection conn = null ;
Statement stmt = null ;
try {
conn = JdbcUtils. getConnection ( ) ;
String sql = "insert into student(name,age,gender,address) values('赵又廷',49,'男','西安市碑林区'),('朱亚文',38,'男','西安市碑林区')" ;
stmt = conn. createStatement ( ) ;
int count = stmt. executeUpdate ( sql) ;
if ( count> 0 ) {
System. out. println ( "影响了" + count+ "行" ) ;
}
} catch ( SQLException e) {
e. printStackTrace ( ) ;
} finally {
JdbcUtils. close ( stmt, conn) ;
}
查询:
需求: 需要查询mydb_05数据库下面的emp表, 将查询的结果封装到员工类中
将员工类存储ArrayList< Employee> , 遍历集合展示所有员工数据
ArrayList< Employee> list = new ArrayList < Employee> ( ) ;
Employee emp = null ;
conn = JdbcUtils. getConnection ( ) ;
String sql = "select * from emp" ;
stmt = conn. createStatement ( ) ;
rs = stmt. executeQuery ( sql) ;
while ( rs. next ( ) ) {
emp = new Employee ( ) ;
int id = rs. getInt ( "id" ) ;
String name = rs. getString ( "name" ) ;
String gender = rs. getString ( "gender" ) ;
int salary = rs. getInt ( "salary" ) ;
Date join_date = rs. getDate ( "join_date" ) ;
emp. setId ( id) ;
emp. setName ( name) ;
emp. setGender ( gender) ;
emp. setSalary ( salary) ;
emp. setJoin_date ( join_date) ;
list. add ( emp) ;
}
return list ;
if ( list!= null) {
for ( Employee emp : list) {
System. out. println ( emp. getId ( ) + "\t" +
emp. getName ( ) + "\t" + emp. getGender ( ) + "\t" + emp. getSalary ( ) + "\t" +
emp. getJoin_date ( ) ) ;
}
}
引入PreparedStaement 基本使用
引入PreparedStaement 基本使用
有效防止sql注入/ 可以提高开发效率
例:
使用预编译对象PreparedStatement来将给员工表添加一条数据
DML语句
insert into 表名. . .
Connection conn = null ;
PreparedStatement stmt = null ;
try {
conn = JdbcUtils. getConnection ( ) ;
String sql =
"insert into emp (name,gender,salary,join_date) values(?,?,?,?)" ;
stmt = conn. prepareStatement ( sql) ;
stmt. setString ( 1 , "诸葛亮2" ) ;
stmt. setString ( 2 , "男" ) ;
stmt. setInt ( 3 , 12000 ) ;
stmt. setString ( 4 , "2011-11-10" ) ;
int count = stmt. executeUpdate ( ) ;
System. out. println ( "影响了" + count+ "行" ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
} finally {
JdbcUtils. close ( stmt, conn) ;
}
连接池
连接池技术:
为了方便连接对象频繁使用( 在一定连接数量: 符合连接池的参数)
1. c3p0: 连接
2.D ruid: 德鲁伊 连接池
导入核心jar包-- -- DruidDataSource-- - > DataSource -- -- 获取连接对象
+ 导入驱动jar包+ dbutils. jar ( 通用的工具类)
封装: JDBCUtils工具类
声明数据源 DruidDataSource
static {
读取druid. properites配置文件
加载到Properties属性集合类中
DuridDataSourceFactory. creatDataSoruce ( Properties prop) ( 强制类型转换)
}
获取连接对象Connection
关闭资源
3. 通用工具类: Dbutils的使用:
针对Dao层( Data Access Object: 数据访问对象)
增删改查的操作
1 ) 创建执行对象
QueryRunner ( DataSource ds)
2 ) 准备sql : 参数化的sql
update user set name = ? where id = ? ;
insert into user ( name, gender, address) values ( ? , ? , ? ) ;
delete from user where id = ?
select u. name, u. gender, u. address from user u where id = ?
select * frmo user ;
通过当前id获取一条记录-- - > 封装到实体类中
3 ) 执行更新
QueryRunner
update ( String sql, Object. . . parameters)
query ( String sql, ResultSetHandler< ? > rs, Object . . . parame)
ResultSetHandler 接口
new BeanHandler < ? > ( Class< ? > clazz) : 将查询的某一条记录封装到某个对象中
new BeanListHandler < ? > ( Class< ? > clazz) : 将查询的多条记录封装到List< ? > 集合中
new ScalarHandler < > ( ) -- -- > 查询单行当列的
举例: 查询当前数据的总记录数
select count ( id) from user; 6
对Druid连接池进行封装
封装工具类
1 ) 使用连接池获取连接对象 -- -- Druid连接池
DruidDataSourceFactory. createDataSource ( Properties prop) -- - > javax. sql. DataSource
2 ) 封装获取连接的方法
mygetConnection ( ) -- -- - DataSource对象可以调用getConnection ( )
3 ) 释放资源
public class MyJdbcUtils {
private static DataSource ds ;
private MyJdbcUtils ( ) { }
static {
try {
Properties prop = new Properties ( ) ;
InputStream inputStream = MyJdbcUtils. class .
getClassLoader ( ) . getResourceAsStream ( "druid.properties" ) ;
prop. load ( inputStream) ;
ds = DruidDataSourceFactory. createDataSource ( prop) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
public static Connection getConnection ( ) {
Connection conn = null ;
try {
conn = ds. getConnection ( ) ;
return conn ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
return null ;
}
public static DataSource getDataSource ( ) {
return ds;
}
public static void close ( ResultSet rs, PreparedStatement stmt, Connection conn) {
if ( rs!= null) {
try {
rs. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
if ( stmt!= null) {
try {
stmt. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
if ( conn!= null) {
try {
conn. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
}
public static void close ( PreparedStatement stmt, Connection conn) {
close ( null, stmt, conn) ;
}
public static void main ( String[ ] args) {
DataSource ds = MyJdbcUtils. getDataSource ( ) ;
System. out. println ( ds) ;
Connection conn = MyJdbcUtils. getConnection ( ) ;
System. out. println ( conn) ;
}
}
使用连接池DbUtils对数据进行增删改查
@Override
public void add ( User u) {
try {
QueryRunner qr= new QueryRunner ( MyJdbcUtils. getDataSource ( ) ) ;
String sql= "insert into user (id,username,PASSWORD,email,birthday,address) values (?,?,?,?,?,?)" ;
int count= qr. update ( sql, u. getId ( ) , u. getUsername ( ) ,
u. getPassword ( ) , u. getEmail ( ) , u. getBirthday ( ) , u. getAddress ( ) ) ;
System. out. println ( count) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
@Override
public void delete ( int id) {
try {
QueryRunner qr= new QueryRunner ( MyJdbcUtils. getDataSource ( ) ) ;
String sql= "delete from user where id=?" ;
int count= qr. update ( sql, id) ;
System. out. println ( count) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
@Override
public void update ( User u) {
try {
QueryRunner qr= new QueryRunner ( MyJdbcUtils. getDataSource ( ) ) ;
String sql= "update user set
username= ? , PASSWORD= ? , email= ? , birthday= ? , address= ? where id= ? ";
int count= qr. update ( sql, u. getUsername ( ) , u. getPassword ( ) ,
u. getEmail ( ) , u. getBirthday ( ) , u. getAddress ( ) , u. getId ( ) ) ;
System. out. println ( count) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
@Override
public User getById ( int id) {
try {
QueryRunner qr= new QueryRunner ( MyJdbcUtils. getDataSource ( ) ) ;
String sql= "select * from user where id=?" ;
User us= qr. query ( sql, new BeanHandler < User> ( User. class ) , id) ;
return us;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
return null;
}
@Override
public List< User> findAll ( ) {
try {
QueryRunner qr= new QueryRunner ( MyJdbcUtils. getDataSource ( ) ) ;
String sql= "select*from user" ;
List< User> list= qr. query ( sql, new BeanListHandler < User> ( User. class ) ) ;
return list;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
return null;
}
@Override
public int getCount ( ) {
try {
QueryRunner qr= new QueryRunner ( MyJdbcUtils. getDataSource ( ) ) ;
String sql= "select*from user" ;
List< User> list= qr. query ( sql, new BeanListHandler < User> ( User. class ) ) ;
return list. size ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
return 0 ;
}
Jdbc中涉及相关的核心类以及核心接口的API
1. com. mysql. jdbc. Driver -- -- > class 驱动类
implements java. sql. Driver 接口 ( 驱动程序)
Class. forName ( "com.mysql.jdbc.Driver" ) ; 为了保证向下兼容性( JDK6以前)
com. mysql. jdbc. Drvier-- -- - > 这个类一加载, 静态代码也会随之加载
static {
DriverManager. registerDriver ( Driver driver) -- -- 这里面已经注册过了
}
2. 获取数据连接对象
核心类
DriverManager -- -- -- -- > 驱动管理类-- -- 管理JDBC驱动程序服务!
成员方法
public static void registerDriver ( Driver driver) : 注册驱动
public static Connection getConnection (
String url,
String user,
String password) : 获取数据库的连接对象
通过创建系统资源发送到数据库的一种url请求
参数1 :
url: 统一资源定位符
协议: / / 域名或者ip地址: 端口号/ 链接具体地址
jdbc: mysql: / / localhost: 3306 / 数据库名称
参数2 : 用户名: root用户
参数3 : 密码
3. Connection-- - java. sql. Connection
与指定的数据库的一种会话! -- -- 通过系统资源获取
成员方法
有关事务管理相关的方法
void setAutoCommit ( boolean autoCommit) : 设置数据库的提交方式 :
参数为true : 表示自动提交
参数为false : 表示禁用自动提交
void rollback ( ) : 事务的回滚
void commit ( ) : 事务的提交
与数据库执行对象相关方法
Statement createStatement ( ) : 创建Statement对象, 将指定sql发送到数据库中
PreparedStatement prepareStatement ( String sql) : 将
类似于
insert into account values ( ? , ? , ? ) ; sql语句先进行预编译
4. Statement -- -- java. sql. Statement
执行对象: 执行静态sql语句
静态的sql语句
insert into account values ( 1 , '张三' , 1000 ) , ( 2 , '李四' , 1000 ) ;
update account set balance = balance - 500 where id = 1 ;
成员方法
int executeUpdate ( String sql) : 通过Statement将静态sql语句发送到数据库中进行操作
执行增删该
ResultSet executeQuery ( String sql) : 执行查询语句select. . .
select * from student ;
5. PreparedStatement -- -- java. sql. PreparedStatement: 预编译对象
insert into account values ( ? , ? , ? ) ;
int executeUpdate ( ) : 对预编译对象中sql语句直接操作!
6. ResultSet -- -- java. sql. ResultSet: 表示数据库结果集的数据表
成员方法
boolean next ( ) : 判断下一行是否存在有效数据!
XXX getXXX ( int columnIndex) : 根据列的索引值获取表中结果数据: 索引值1 开始
如果是第一列, 则为1
. . . . 第二列, 则为2
XXX getXXX ( String columnLabel) : 根据列的名称获取