一、JDBC API
主要功能:与数据库建立连接、执行SQL语句、处理结果
- DriverManager:依赖数据库的不同,管理JDBC驱动
- Connection:负责链接数据库并担任传输数据的任务
- Statement:由Connection产生,负责执行SQL语句
- ResultSet:负责保存Statement执行后所产生的查询结果
二、JDBC加载
try{
Class.forName(JDBC驱动类);//加载JDCB驱动
}
......
try{
Connention con = DriverManager.getConnection(URL,数据库名称,密码);//与数据库建立连接(URKL用来标识数据库)
Statement stmt = con.creatStatement();
ResultSet rs = stmt.executeQuery("SELECT a,b,c FROM table1;");//发送sql语句,并得到返回结果
while(rs.next()){
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}//处理返回结果
}catch{
......
}finally{
rs.close;
stmt.close;
con.close;
}
......
三、JDBC连接
Class.forName("com.mysql.jdbc.Driver")//加载驱动,需要下载相关数据库的专用驱动
Connection conn = DriverManager.getConnect("jdbc:mysql://localhost:3306/db_name","root", "0000")//使用数据库用户和密码建立连接。注意:mysql8需要在URL中配置时区
MySQL8:
驱动:com.mysql.cj.jdbc.Driver
URL:jdbc:mysql://localhost:3306/mysql?characterEncoding=utf8&useSSL=fals
e&serverTimezone=UTC&rewriteBatchedStatements=true
MySQL5:
驱动: com.mysql.jdbc.Driver
URL:jdbc:mysql://localhost:3306/school?useUnicode=true&characterEnco
ding=utf8
四、API常用方法
Statement
方法名 |
说明 |
ResultSet executeQuery(String sql) |
执行SQL语句查询并获取到ResultSet对象 |
int executeUpdate(String sql) |
可以执行插入,删除,更新等操作,返回值是执行该操作所影响的行数 |
boolean execute(String sql) |
可以执行任意sql语句,然后获得一个布尔值,表示是否返回ResultSet |
int getUpdateCount() |
获取execute后的操作行数 |
ResultSet
方法名 |
说明 |
boolean next() |
将游标向下移动一行 |
boolean previous() |
将游标向上移动一行 |
void close() |
关闭ResultSet对象 |
int getInt(int colIndex) |
以int形式获取结果集当前行指定列号值 |
int getInt(String colLabel) |
以int形式获取结果集当前行指定列名值 |
float getFloat(int colIndex) |
以float形式获取结果集当前行指定列号值 |
float getFloat(String colLabel) |
以float形式获取结果集当前行指定列名值 |
String getString(int colIndex) |
以String形式获取结果集当前行指定列号值 |
String getString(String colLabel) |
以String形式获取结果集当前行指定列名值 |
五、PreparedStatement
1.为什么要使用PreparedStatement?
当我们通过数据库验证用户名密码时,普通的Statement使用的sql语句为拼接字符串,及“SELECT * FROM table1 WHERE userName=¥{用户输入的用户名},password=¥{用户输入的密码}”,此时,一旦密码参数输入为xxx”or“1"="1
,sql语句就会变成*(省略前面语句) or 1 = 1
,此语句绝对正确,也就是说前面的sql语句全部失效了,此时就会返回数据库的全部内容(sql注入),对数据库安全来说是极大的隐患。
2.PreparedStatement接口
PreparedStatement继承自Statement接口,比Statement使用起来更加灵活,更有效率。
- 提高了代码的可读性与维护性
- 提高了SQL语句执行的性能
- 提高了安全性
3.接口使用
Connection conn = null;
PreparedStatement pstmt = null;//声明PreparedStatement变量
String sql="update table set name=?,pwd=? where id=?";//将参数换位占位符,避免出现sql注入
pstmt = conn.prepareStatement(sql);//创建PreparedStatement对象
pstmt.setInt(1, “吴彦祖”);
pstmt.setInt(2, “123456”);
pstmt.setInt(3, 1);//设置每个输入参数的值,参数1的序号与sql语句中的参数一一对应,顺序不能乱
pstmt.executeUpdate();//执行sql语句
......
pstmt.close();
conn.close();