Java - JDBC
文章目录
1.快速入门
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection c= DriverManager.getConnection("jdbc:mysql://localhost:3306/wtf02","root","root");
String sql="update why set money =500 where id=0";
Statement s=c.createStatement();
int count=s.executeUpdate(sql);
System.out.println(count);
c.close();
s.close();
}
注: 结束时先释放后面创建的资源,再释放前面的
2.各个类详解
<1>各个对象
(1) DriverManager:
功能: 注册驱动; 获取数据库连接:
① 注册驱动 (Mysql5以后可以省略)
Class.forName("com.mysql.jdbc.Driver");
② 获取数据库连接:
方法:Connection c= DriverManager.getConnection(String url1,String user,String password)
url:指定连接路径:
jdbc:mysql://ip地址(域名):端口号/数据库名称
如果连接本机SQL服务器,可省略为: jdbc:mysql:///数据库名称
username: 用户名(root)
password: 密码(root)
(2)Connection: 数据库连接对象
① 获取执行sql的对象
Statement createStatement()
PreparedStatement prepareStatement(String sql)
② 开启事务:setAutoCommit(boolean autoCommit)
:设置参数为false,开启事务
提交事务:commit()
回滚事务:rollback()
(3)Statement: 执行sql的对象
执行sql
① excuteUpdate(String sql):
可以执行DML、DDL语句(返回值为改变的行数)
② ResultSet executeQuery(String sql):
执行DQL (Select) 语句
public static void main(String[] args) {
Statement stmt=null;//要定义在外面!
Connection con=null;
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
con= DriverManager.getConnection("jdbc:mysql:///wtf02","root","root");
//3.定义sql
String sql="update why set money =400 where id=0";
//4.获取执行sql对象
stmt=con.createStatement();
//5.执行sql
int count = stmt.executeUpdate(sql);
//6.处理结果
System.out.println(count);
}
//7.处理异常
catch (ClassNotFoundException | SQLException e){
e.printStackTrace();
}
//8.释放资源
finally {
if(stmt!=null){
try {
stmt.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if (con!=null){
try {
con.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}
(4)ResultSet: 结果集对象
补充知识:
从SQL表中读取数据需要用到游标, 游标默认指向首行 (表头行)
-
next()
: 游标向下移动一行,判断当前行是否是最后一行末尾(是否有数据),如果是,则返回false,如果不是则返回true -
getXxx(参数)
:获取数据
* Xxx:代表数据类型 如: getInt() , getString()
* 参数:
1. int:代表列的编号,从1开始 如: getString(1)
2. String:代表列名称。 如: getDouble(“balance”) -
使用步骤:
1. 游标向下移动一行
2. 判断是否有数据
3. 获取数据
while(rs.next()){ //循环判断游标是否是最后一行末尾。
//获取数据
String name = rs.getString("name");
int money = rs.getInt(3);
String location = rs.getString("Location");
System.out.println( name+" " + money + " " + location);
}
(5)PreparedStatement: 执行sql的对象
- sql 注入: 由于拼接sql时,有一些sql特殊关键字参与拼接,造成安全性问题。需要使用
PreparedStatement
对象解决
①读取username 和 password 到变量
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
②定义sql并执行
String sql = "select * from user where username = '"+username+"' and password = '"+password+"' ";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
(6) JDBC 管理事务
- 开启事务:setAutoCommit(boolean autoCommit) :调用该方法设置参数为false,即开启事务 (在执行sql之前开启事务)
- 提交事务:commit() (当所有sql都执行完提交事务)
- 回滚事务:rollback() (在catch中回滚事务)
(7) 数据库连接池
概念:存放数据库连接的对象的容器
实现: javax.sql 包下的标准接口 DataSource:
方法:
①获取连接: getConnection()
②归还连接: Connection.close()
- C3P0
①导包(2个)
②定义配置文件:
③创建数据库连接池对象 ComboPooledDataSource
④获取连接 getConnection
DataSource ds = new ComboPooledDataSource();
Connection conn = ds.getConnection(); 放置于 src 目录下的c3p0.properties 或 c3p0-config.xml
- Druid
①导包
②定义配置文件
③加载配置文件
Properties pro=new Properties();
InputStream is=DruidDemo.class.getClassloader().getResourceAsStream("路径");
pro.load(is);
④获取连接池对象
DataSource ds=DuriDataSOurceFactory.createDataSource(pro);
⑤获取连接
Connection conn=ds.getConnection();
System.out.println(conn);
(8) Spring JDBC
- JDBC Templete 创建对象:
JdbcTemplate template = new JdbcTemplate(ds);
- 语句:
update(): 执行DML语句。增、删、改语句
定义sql语句
String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
int count = template.update(sql, 1015, "二聪", 0);
queryForMap(): 查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合
String sql = "select * from emp where id = ? or id = ?";
Map<String, Object> map = template.queryForMap(sql, 1001,1002);
queryForList(): 查询结果将结果集封装为list集合
注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中
String sql = "select * from emp";
List<Map<String, Object>> list = template.queryForList(sql);
query(): 查询结果并结果封装,query的参数:RowMapper
queryForObject:查询结果并封装为对象(一般用于聚合函数的查询)
查询总记录
String sql = "select count(id) from emp";
Long total = template.queryForObject(sql, Long.class);