JDBC入门
JDBC(Java DataBase Connectivity),本质上是接口(规范),用来建立java与数据库之间的连接。
- SQL语句主要分为两大类,①增删改查 ②查
1、jdbc操作
1>添加jar包
2>加载驱动
3>获取与数据库的连接
需要提供url、数据库的用户名、密码
4>创建通道,发送sql
5>处理结果集类
6>关闭资源
- 下面的driver,url,username,password可以封装起来【使用自定义JDBCUtils,将其封装为常量】
public class Demo01 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");//1、加载类 2、创建对象
//获取连接
String url = "jdbc:mysql://test:characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
//创建sql语句[此处以查询为例] => 不同的sql语句对应不同的操作,对应不同的API
String sql = "select id,username,age from dept";
rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id"); //写列名
// int id1 = rs.getInt(1); //写列的序号
String employeeName = rs.getString("employ_name");
int age = rs.getInt("age");
System.out.println(id + "," + employeeName + "," + age);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(stmt != null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
2、SQL注入问题
SQL注入:拼接特殊的SQL语句,获取到不该获取的数据
String name = "abc";
Stirng pwd = " fad 'or' 1 '=' 1 "
//使用or,最后不管输入什么用户名,最后SQL执行都会成功[恒成立]
select * from usrs where username = 'abc' and pwd = ' fad 'or' 1 '=' 1 ';
- 解决办法:
Java提供了PreparedStatement,用?作为占位符来替换
preparedStatement在将参数传入SQL语句中,将参数中的引号也作为参数【使用转义字符,避免SQL注入】
3、事务问题及其他操作
- jdbc事务默认自动提交
- conn.setAutoCommit(false);//设置事务为手动提交
try{
...
conn.setAutoCommit(false);//手动提交事务
//第一条SQL语句
//第二条SQL语句
conn.commit();
...
}catch(Exception e){
e.printStacktrace();
conn.rollback(); //有异常发生,回滚事务
}finally{
}
- 打点事务(savePoint)
不管怎么样,都要执行。例如:银行转账,就算转账失败,也要扣除账户50元,类似于手续费。
//1、新建保存点
SavePoint sp = null;
//2、设置保存点
sp = conn.setSavePoint();
//3、发生异常时,回滚到保存点
conn.rollback(sp);
- 批处理
循环执行同样的操作,可以考虑使用批处理
步骤:
1、for(){
pstmt.addBatch(“sql语句”);
}
2、pstmt.executeBath();
3、如果数据量极大,可以分批处理,例如10000条数据,可以每1000条,批处理一次。
-
获取自增主键
pstmt = conn.preparedStatement(“sql语句”, Statement.RETURN_GENERATED_KEYS);
rs = pstmt.getGeneratedKeys(); -
CallableStatement:操作SQL函数