JDBC
JDBC规范介绍:
1、JDBC是JAVAEE的一种规范
2、用于指定JAVA类与关系型数据库服务器【MySql、Oracle、SQL Server】的沟通规则
3、JDBC规范提供的接口存在与JDK中(java.sql包)
4、JDBC规范接口实现类有关系性数据库服务器厂商以jar包的形式提供
JDBC规范的调用流程
1、注册驱动
2、获取连接
3、获取数据库操作对象
4、执行sql
5、处理查询结果集(若只应用了DML就不需要这一步)
6、释放资源
代码展示:
import java.sql.*;
import static java.lang.Class.*;
public class jdbctest01 {
public static void main(String[] args) {
Connection conn =null;
Statement st = null;
ResultSet rs = null;
try {
//1、注册驱动
Class.forName(“com.mysql.cj.jdbc.Driver”);
//2、获取连接
conn = DriverManager.getConnection
(“jdbc:mysql://localhost:3306/whfirstbase”,“root”,“2464wh666666”);
//3、获取数据库操作对象
st=conn.createStatement();
//4、执行sql
String sql = “select ename,sal,deptno from emp”;
rs= st.executeQuery(sql);
//5、处理查询结果集
while(rs.next()){
System.out.println(
rs.getString(1)+“,”+
rs.getString(2)+“,”+
rs.getString(3)
);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
//6、释放资源
if (rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} if (st!=null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
解决sql注入问题(部分代码)
private static Boolean loginbase(Map<String, String> login) {
Boolean bol =false;
Connection conn=null;
/**
* Statement stm= null;
* 要解决sql注入问题需要把 statement 接口换成他的子接口 preparedstatement
* preparedstatement接口会对sql语句进性预编译 需要用户填写的部分用 ? 即占位符 进性表示
*/
PreparedStatement ps = null;
ResultSet rs= null;
try {
//1、注册驱动
Class.forName(“com.mysql.cj.jdbc.Driver”);
//2、获取连接
conn = DriverManager.getConnection
(“jdbc:mysql://localhost:3306/loginbase”,“root”,“2464wh666666”);
//3、获取数据库操作对象
/**
* stm = conn.createStatement();
* 要换成conn。prepare
*/
String sql =“select * from user where name=?and password=?”;
ps=conn.prepareStatement(sql);
//4、执行sql语句
/**
* String sql =“select * from user where name='”+login.get(“username”)+“‘and password=’”+login.get(“password”)+“'”;
* 这一步要换到第三步前执行进性预处理
* 然后调用ps的setString方法替换 ?
* 替换时要记住 JDBC 所有下标都是从 1 开始
*/
ps.setString(1,login.get(“username”));
ps.setString(2,login.get(“password”));
rs = ps.executeQuery();
//5、处理查询结果集
if (rs.next()) bol=true;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
//6、释放资源
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return bol;
}
事务控制
JDBC 默认事务是自动提交的需要调用
conn.setautocommit() 方法关闭自动提交
conn.commit 手动提交
conn.rollback 手动回滚