JAVA Web学习笔记8 JDBC
JDBC概念JDBC就是使用Java操作关系型数据库的一套API全称(Java DataBase Connectivity )Java数据库连接步骤:0、创建工程,导入驱动jar包1、注册驱动Class.forName("com.mysql.jdbc.Driver")2、获取连接Connection conn =DriverManager.getConnection(url,username,pa
JDBC概念
- JDBC就是使用Java操作关系型数据库的一套API
- 全称(Java DataBase Connectivity )Java数据库连接
步骤:
0、创建工程,导入驱动jar包
1、注册驱动
Class.forName("com.mysql.jdbc.Driver")
2、获取连接
Connection conn =DriverManager.getConnection(url,username,password);
3、定义SQL语句
String sql="update ...."
4、获取执行SQL对象
Statement stmt=conn.createStatement();
5、执行SQL
stmt.executeUpdate(sql);
6、处理返回结果
7、释放资源
package com.itheima.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
String url="jdbc:mysql://127.0.0.1:3306/mysql";
String username="root";
String password="1234";
Connection conn= DriverManager.getConnection(url,username,password);
//定义sql
String Sql="update account set money =2000 where id=1";
//获取执行SQL的对象 statement
Statement stmt=conn.createStatement();
//执行SQL并返回值 返回1则说明执行成功
int count=stmt.executeUpdate(Sql);
System.out.println(count);
//释放资源
stmt.close();
conn.close();
}
}
执行结果:
JDBC API之DriverManager
配置useSSL=false解决警示
这样使用:
JDBC API之Connection
使用ctrl alt +T添加try catch throw
public class JDBCDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
String url="jdbc:mysql://127.0.0.1:3306/mysql";
String username="root";
String password="1234";
Connection conn= DriverManager.getConnection(url,username,password);
//定义sql
String Sql1="update account set money =3000 where id=1";
String Sql2="update account set money =3000 where id=2";
//获取执行SQL的对象 statement
Statement stmt=conn.createStatement();
try {
//开启事务
conn.setAutoCommit(false);
//执行SQL并返回值 返回1则说明执行成功
int count1=stmt.executeUpdate(Sql1);
System.out.println(count1);
int count2=stmt.executeUpdate(Sql2);
System.out.println(count2);
} catch (Exception e) {
e.printStackTrace();
//提交事务
conn.commit();
}
//释放资源
stmt.close();
conn.close();
}
}
JDBC API之Statement
也就是对于DML和DDL的返回值要进行不同的判断,DML返回值>0说明执行成功了,其他就是失败,而DDL即使成功了也可能返回值是0。
JDBC API之ResultSet
package com.itheima.jdbc;
import org.junit.Test;
import java.sql.*;
public class JDBCResultSetDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException, SQLException {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
String url="jdbc:mysql://127.0.0.1:3306/mysql";
String username="root";
String password="1234";
Connection conn= DriverManager.getConnection(url,username,password);
//3、定义sql
String sql="select * from account";
//4、获取statement对象
Statement stmt = conn.createStatement();
//5、执行sql
ResultSet rs=stmt.executeQuery(sql);
//6、处理结果,遍历rs中所有数据
while (rs.next()){
int id=rs.getInt(1);
String name =rs.getString(2);
double money=rs.getDouble(3);
/*上面三行可以替换为
int id=rs.getInt("id");
String name =rs.getString("name");
double money=rs.getDouble("money");
*/
System.out.println(id);
System.out.println(name);
System.out.println(money);
System.out.println("-------");
}
//释放资源
rs.close();
stmt.close();
conn.close();
}
}
Account
package pojo;
public class Account {
private int id;
private String name;
private double money;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
@Override
public String toString() {
return "Acoount{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
Demo
package pojo;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ResultSetDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException, SQLException {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
String url="jdbc:mysql://127.0.0.1:3306/mysql";
String username="root";
String password="1234";
Connection conn= DriverManager.getConnection(url,username,password);
//3、定义sql
String sql="select * from account";
//4、获取statement对象
Statement stmt = conn.createStatement();
//5、执行sql
ResultSet rs=stmt.executeQuery(sql);
//创建集合
List<Account> list=new ArrayList<Account>();
//6、处理结果,遍历rs中所有数据
while (rs.next()){
Account ac=new Account();
int id=rs.getInt("id");
String name =rs.getString("name");
double money=rs.getDouble("money");
ac.setId(id);
ac.setName(name);
ac.setMoney(money);
list.add(ac);
}
System.out.println(list);System.out.println("-------");
//释放资源
rs.close();
stmt.close();
conn.close();
}
}
JDBC之PreparedStatement
SQL注入
创建表
drop table if exists tb_user;
create table tb_user(
id int,
username varchar(20),
password varchar(32)
);
insert into tb_user values(1,"zhangsan",'123'),(2,'list','234');
select * from tb_user;
package com.itheima.jdbc;
import java.sql.*;
public class JDBCSQLinject {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
String url="jdbc:mysql://127.0.0.1:3306/mysql";
String username="root";
String password="1234";
Connection conn= DriverManager.getConnection(url,username,password);
//接收用户输入的账号和密码
String name="dasdassa";
String pwd="3123123";
String sql="select * from tb_user where username='"+name+"' and password='"+pwd+"' ";
// select * from tb_user where username='dasdassa' and password='' or '1' = '1'
//获取stmt对象
Statement stmt = conn.createStatement();
//执行sql
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
if (rs.next()){
System.out.println("登陆成功");
}else{
System.out.println("登陆失败");
}
}
}
如果登陆密码为:3123123
执行结果为:
如果登陆密码为:String pwd=“’ or ‘1’ = '1”;
执行结果:
原因是在sql数据库中的执行结果会将Java中的" "变成’ ',那么总的执行代码为:
select * from tb_user where username='dasdassa' and password='' or '1' = '1' ;
password=""密码等于空是一个false但后面’1’='1’就是true
false and false or true==true.
使用preparedStatement对sql语句进行转义,这样就防止了sql注入
package com.itheima.jdbc;
import java.sql.*;
public class JDBCPreparedStatementDemo {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
String url="jdbc:mysql://127.0.0.1:3306/mysql";
String username="root";
String password="1234";
Connection conn= DriverManager.getConnection(url,username,password);
//接收用户输入的账号和密码
String name="zhangsan";
String pwd="' or '1'='1";
//使用?作为占位符
String sql="select * from tb_user where username=? and password=?";
// select * from tb_user where username='dasdassa' and password='' or '1' = '1'
//获取stmt对象
PreparedStatement pstmt = conn.prepareStatement(sql);
//设置?的值
pstmt.setString(1,name);
pstmt.setString(2,pwd);
//执行sql
ResultSet rs=pstmt.executeQuery();
System.out.println(sql);
if (rs.next()){
System.out.println("登陆成功");
}else{
System.out.println("登陆失败");
}
rs.close();
pstmt.close();
conn.close();
}
}
PreparedStatement 预编译功能开启:useServerPrepStmts=true
PreparedStatement原理:
1.在获取PreparedStatement对象时, 将sq|语句发 送给mysql服务器进行检查,编译(这些步骤很耗时)。
2.执行时就不用再进行这些步骤 了,速度更快。
3.如果sq|模板一样,则只需要进行一次检查、编译。
//获取连接
String url="jdbc:mysql://127.0.0.1:3306/mysql?useSSl=false&useServerPrepStmts=true";
String username="root";
String password="1234";
Connection conn= DriverManager.getConnection(url,username,password);
数据库连接池
package druid;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;
public class DruidDemo {
public static void main(String[] args) throws Exception {
//1、导入jar包
//2、定义配置文件
//3、加载配置文件
Properties prop =new Properties();
prop.load(new FileInputStream("src/druid.properties"));
//4、获取连接池对象
DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);
//5、获取数据库连接
Connection connection=dataSource.getConnection();
System.out.println(connection);
// System.out.println(System.getProperty("user.dir"));
}
}
更多推荐
所有评论(0)