MySQL(JDBC)狂神笔记
10. JDBC
10.1数据库驱动

程序会通过数据库驱动和数据库打交道
10.2 JDBC

需要:
java.sql
javax.sql
还需要一个导入数据库驱动包 mysql-connector-java某版本.jar
10.3 第一个JDBC程序
创建测试数据库
CREATE DATABASE jdbcStudy CHARACTER SET utf8 COLLATE utf8_general_ci;
USE jdbcStudy;
CREATE TABLE users(
id int PRIMARY KEY,
NAME VARCHAR(40),
PASSWORD VARCHAR(40),
email VARCHAR(60),
birthday DATE
);
INSERT INTO users(id,NAME,PASSWORD,email,birthday)
VALUES(1,'zhansan','123456','zs@sina.com','1980-12-04'),
(2,'lisi','123456','lisi@sina.com','1981-12-04'),
(3,'wangwu','123456','wangwu@sina.com','1979-12-04');
- 创建一个普通项目
- 导入数据库驱动
![image]()
- 编写测试代码
//1.加载驱动 抛出异常,因为可能找不到
Class.forName("com.mysql.jdbc.Driver");//固定写法
//2.用户信息和url
//useUnicode=true&characterEncoding=utf8&useSSL=true 设置支持中文编码,设置字符集utf8,设置安全连接
String url="jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username="root";
String password="root";
//3.连接成功,数据库对象 Connection代表数据库
Connection connection = DriverManager.getConnection(url,username,password);
//4.执行SQL的对象 Statement执行SQL的对象
Statement statement=connection.createStatement();
//5.执行SQL的对象 去 执行SQL 可能存在结果,查看返回结果
String sql="SELECT * FROM users";
ResultSet resultSet=statement.executeQuery(sql);//返回的结果集,封装了所有的查询结果
while (resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("name="+resultSet.getObject("NAME"));
System.out.println("pwd="+resultSet.getObject("PASSWORD"));
System.out.println("email="+resultSet.getObject("email"));
System.out.println("birthday="+resultSet.getObject("birthday"));
System.out.println("===============================");
}
//6.释放连接
resultSet.close();
statement.close();
connection.close();
}
错误:Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure错误:Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
- url username password 写错
- jdbc驱动版本不对
![image]()
![image]()
![image]()
![image]()
![image]()
![image]()
![image]()
10.4 statement对象




10.5 封装
db.properties配置文件可以防止src
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=root
配置类封装方法
private static String driver=null;
private static String url=null;
private static String username=null;
private static String password=null;
static {
try {
InputStream inputStream=JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties=new Properties();
properties.load(inputStream);
driver= properties.getProperty("driver");
url= properties.getProperty("url");
username= properties.getProperty("username");
password= properties.getProperty("password");
//1.驱动只用加载一次 所以写在static
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
//释放连接资源
public static void release(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
if(resultSet!=null){
resultSet.close();
}
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
}
执行操作如insert
Connection connection=null;
Statement statement=null;
ResultSet resultSet=null;//finally捕获不到必须先定义
try {
connection=JdbcUtils.getConnection(); //1.获取连接
statement=connection.createStatement();//2.获得SQL的执行对象
String sql="INSERT INTO users(id,NAME,PASSWORD,email,birthday)\n" +
"VALUES(4,'huihui','123456','hui@sina.com','1998-10-04')";
int num=statement.executeUpdate(sql);//返回受影响行数 增删改都用executeUpdate
if(num>0){
System.out.println("插入成功!");
}
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
JdbcUtils.release(connection,statement,resultSet);
}
}
10.6 sql注入

public static void main(String[] args){
//正常登录
//login("huihui","123456");
login("'or'1=1","'or'1=1");
}
//登录业务
public static void login(String username,String password){
Connection connection=null;
Statement statement=null;
ResultSet resultSet=null;//finally捕获不到必须先定义
try {
connection=JdbcUtils.getConnection(); //1.获取连接
statement=connection.createStatement();//2.获得SQL的执行对象
//sql怎么拼接
//SELECT * FROM users WHERE `NAME`='huihui' AND `PASSWORD`='123456'
//SELECT * FROM users WHERE `NAME`=''or'1=1' AND `PASSWORD`=''or'1=1'
String sql="select * from users where `NAME`='"+username+"' AND `PASSWORD`='"+password+"'";
resultSet=statement.executeQuery(sql);//返回受影响行数
while (resultSet.next()){
System.out.println(resultSet.getString("NAME"));
System.out.println(resultSet.getString("PASSWORD"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
try {
JdbcUtils.release(connection,statement,resultSet);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
10.7 PreparedStatement对象
PreparedStatement 可以防止SQL注入,效率更好
插入示例
Connection connection=null;
PreparedStatement preparedStatement =null;
try {
connection = JdbcUtils.getConnection(); //1.获取连接
//区别
//使用?占位符代替参数
String sql = "INSERT INTO users(id,NAME,PASSWORD,email,birthday) VALUES(?,?,?,?,?)";
preparedStatement = connection.prepareStatement(sql);//2.预编译SQL,先写SQL,然后不执行
//手动给参数赋值
preparedStatement.setInt(1, 5);//第一个是参数索引
preparedStatement.setString(2, "fengfeng");
preparedStatement.setString(3, "123456");
preparedStatement.setString(4, "ff@qq.com");
//注意点:要把数据库的转化位Java的才可以用
// sql.Date 数据库 java.sql.Date()
// util.Date java new Date().getTime() 获得时间戳
preparedStatement.setDate(5, new java.sql.Date(new Date().getTime()));
//执行
int i=preparedStatement.executeUpdate();
if(i>0){
System.out.println("执行成功");
}
}catch (SQLException e){
e.printStackTrace();
}finally {
try {
JdbcUtils.release(connection,preparedStatement,null);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

10.8 idea连接
选择具体数据库



连接失败查看:

10.9 事务
复习












浙公网安备 33010602011771号