JDBC:一种用于执行SQL语句的Java程序接口,可以为多种关系数据库提供统一访问,由一组用Java语言编写的类和接口组成,是Java访问数据库的标准规范
每个数据库生产厂商需要为自己的数据库设计JDBC的实现类,也就是驱动,来实现java程序对该数据库的访问
JDBC和驱动体现了面向接口的思想
JDBC开发步骤:
1、注册驱动 告知 JVM 使用哪种数据库的驱动
2、获得连接 使用JDBC中的类,完成对驱动对应的(MySQL)数据库的连接
3、获得语句执行平台 通过连接对象获取对SQL语句的执行者对象
4、执行sql语句 使用执行者对象,向数据库执行SQL语句
5、处理结果
6、释放资源
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// TODO Auto-generated method stub
//DriverManager.registerDriver(new Driver());
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
//jdbc:mysql://localhost:3306/数据库
String url = "jdbc:mysql://localhost:3306/goods?characterEncoding=utf-8";
String username = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, username, password);
//获得语句执行平台
Statement sta = conn.createStatement();
//执行sql语句
String sql = "insert into sort(sname,sdesc) values('电子设备','都是骗男人的')";
//int row = sta.executeUpdate(sql);
//int row1 = sta.executeUpdate("delete from sort where sid = 3");
//System.out.println(row);
//查询
String sql1 = "select * from sort";
ResultSet rs = sta.executeQuery(sql1);
while(rs.next()){
System.out.println(rs.getInt("sid")+"..."+rs.getString("sname")+"..."+rs.getString("sdesc"));
}
//释放资源(先开的后关)
rs.close();
sta.close();
conn.close();
}
sql注入问题:
用户登录账号 输入密码时 密码= 12345678 or 1==1 这样不管密码对不对 永远会登录成功 存在风险
预处理对象:用于解决sql注入问题
开发步骤(增删改):
1. 注册驱动
2. 获取连接
3. 获取预处理对象 获得语句执行平台
4. SQL语句占位符设置实际参数
5. 执行SQL语句
6. 释放资源
开发步骤(查询):
1. 注册驱动
2. 获取连接
3. 获取预处理对象
4. SQL语句占位符设置实际参数
5. 执行SQL语句
6. 处理结果集(遍历结果集合)
7. 释放资源
JDBC工具类:封装一个工具类
public class JDBCUtils {
public static Connection getConnection(){
try{
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
String username="root";
String password="123456";
String url="jdbc:mysql://localhost:3306/account?useUnicode=true&characterEncoding=utf-8";
//获得连接
Connection conn=DriverManager.getConnection(url,username,password);
return conn;
}catch(Exception ex){
throw new RuntimeException(ex+"数据库连接失败");
}
}
//关闭数据库的方法
public static void close(ResultSet rs,Statement sta,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(sta!=null){
try {
sta.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void close(Statement sta,Connection conn){
if(sta!=null){
try {
sta.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}