javaweb-数据库
Posted 可能自洽
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javaweb-数据库相关的知识,希望对你有一定的参考价值。
javaweb-数据库
一、mysql 安装配置
参考 MySql 安装配置
二、JDBC
1.下载jar
https://downloads.mysql.com/archives/c-j/
2.粘贴到idea里,然后add
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class test
public static void main(String[] args) throws Exception
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取连接
String url = "jdbc:mysql://127.0.0.1:3306/db1";
String user = "root";
String password = "0000";
Connection connection = DriverManager.getConnection(url, user, password);
// 定义sql语句
String sql = "update stu set name = 123 where id = 1";
// 获取执行sql的对象
Statement statement = connection.createStatement();
// 执行
int count = statement.executeUpdate(sql);
System.out.println(count);
// 关闭
statement.close();
connection.close();
3.JDBC API
3.1DriverManager
注册驱动
Class.forName("com.mysql.jdbc.Driver");
MySQL5之后的驱动jar包,可以省略注册驱动步骤
获取数据库连接
3.2 Connection
获取执行SQL的对象
管理事务
3.3 ResultSet 结果集对象
执行DQL语句返回ResultSet对象
import java.sql.*;
public class test
public static void main(String[] args) throws Exception
String url = "jdbc:mysql://127.0.0.1:3306/db1?useSSL=true";
String user = "root";
String password = "0000";
Connection connection = DriverManager.getConnection(url, user, password);
String sql = "select * from stu";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next())
// 这里可以写列的名称也可以写编号(从1开始)
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
int gender = resultSet.getInt(3);
Date birthday = resultSet.getDate(4);
System.out.println(id);
System.out.println(name);
System.out.println(gender);
System.out.println(birthday);
System.out.println("----------------------");
resultSet.close();
statement.close();
connection.close();
查询stu表里的数据,封装为Stu对象,并存储到ArrayList集合中
定义实体类 Stu
import java.sql.Date;
public class Stu
private int id;
private String name;
private int gender;
private Date birthday;
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 int getGender()
return gender;
public void setGender(int gender)
this.gender = gender;
public Date getBirthday()
return birthday;
public void setBirthday(Date birthday)
this.birthday = birthday;
@Override
public String toString()
return "Stu" +
"id=" + id +
", name='" + name + '\\'' +
", gender=" + gender +
", birthday=" + birthday +
'';
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class test
public static void main(String[] args) throws Exception
String url = "jdbc:mysql://127.0.0.1:3306/db1?useSSL=true";
String user = "root";
String password = "0000";
Connection connection = DriverManager.getConnection(url, user, password);
String sql = "select * from stu";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
List<Stu> stuList = new ArrayList<>();
while (resultSet.next())
Stu stu = new Stu();
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
int gender = resultSet.getInt(3);
Date birthday = resultSet.getDate(4);
stu.setId(id);
stu.setName(name);
stu.setGender(gender);
stu.setBirthday(birthday);
stuList.add(stu);
System.out.println(stuList);
resultSet.close();
statement.close();
connection.close();
3.4 PreparedStatement
预编译SQL语句并执行:预防SQL注入问题
SQL注入是通过操作输入来修改事先定义好的SQL语句,用以达到执行代码对服务器进行攻击的方法。
(1) 创建表
DROP TABLE IF EXISTS tb_user;
CREATE TABLE tb_user (
id INT,
input_username VARCHAR (20),
input_password VARCHAR (20)
);
INSERT INTO tb_user VALUES(1,"giao1","1"),(2,"giao2","2");
SELECT * FROM tb_user;
(2) 体会sql注入
import java.sql.*;
public class test
public static void main(String[] args) throws Exception
String url = "jdbc:mysql://127.0.0.1:3306/db1?useSSL=true";
String user = "root";
String password = "0000";
Connection connection = DriverManager.getConnection(url, user, password);
// String input_name = "giao1";
// String input_password = "1";
String input_name = "asdfasf";
String input_password = "' or '1'='1";
String sql = "select * from tb_user where input_username='" + input_name + "' and input_password='" + input_password + "'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next())
System.out.println("ok");
else
System.out.println("no");
resultSet.close();
statement.close();
connection.close();
(3) 解决sql注入问题
import java.sql.*;
public class test
public static void main(String[] args) throws Exception
String url = "jdbc:mysql://127.0.0.1:3306/db1?useSSL=true";
String user = "root";
String password = "0000";
Connection connection = DriverManager.getConnection(url, user, password);
String input_name = "giao1";
String input_password = "1";
// String input_name = "asdfasf";
// String input_password = "' or '1'='1";
String sql = "select * from tb_user where input_username= ? and input_password=?";
PreparedStatement prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, input_name);
prepareStatement.setString(2, input_password);
ResultSet resultSet = prepareStatement.executeQuery();
if (resultSet.next())
System.out.println("ok");
else
System.out.println("no");
resultSet.close();
prepareStatement.close();
connection.close();
(4)其原理
url后边加这句话useServerPrepStmts=true
my.ini后面加一些命令
[mysql]
default-character-set=utf8
[mysqld]
character-set-server=utf8
default-storage-engine=INNODB
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
log-output=FILE
general-log=1
general_log_file="D:\\mysql.log"
slow-query-log=1
slow_query_log_file="D:\\mysql_slow.log"
long_query_time=2
然后打开cmd,输入services.msc打开服务窗口,点击重新启动,然后D盘就有log文件啦
String url = "jdbc:mysql://127.0.0.1:3306/db1?useSSL=true&useServerPrepStmts=true";
如果把&useServerPrepStmts=true去掉,就没有预编译了
如果 prepareStatement.executeQuery() 执行两次,日志文件只预编译一次,所以性能更高
import java.sql.*;
public class test
public static void main(String[] args) throws Exception
String url = "jdbc:mysql://127.0.0.1:3306/db1?useSSL=true&useServerPrepStmts=true";
String user = "root";
String password = "0000";
Connection connection = DriverManager.getConnection(url, user, password);
// String input_name = "giao1";
// String input_password = "1";
String input_name = "asdfasf";
String input_password = "' or '1'='1";
String sql = "select * from tb_user where input_username= ? and input_password=?";
PreparedStatement prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, input_name);
prepareStatement.setString(2, input_password);
prepareStatement.executeQuery();
prepareStatement.setString(1, "input_name");
prepareStatement.setString(2, "input_password");
prepareStatement.executeQuery();
prepareStatement.close();
connection.close();
3.5 数据库连接池
数据库连接池是个容器,负责分配、管理数据库连接(Connection)
它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个
释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引|起的数据库连接遗漏
好处:资源重用,提升系统响应速度,避免数据库连接遗漏
(1) 下载jar包,然后导入idea
https://repo1.maven.org/maven2/com/alibaba/druid/1.2.8/
(2) 练习
新建 druid.properties 文件并写入配置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db1?useSSL=true&useServerPrepStmts=true
username=root
password=0000
# 初始化连接数
initialSize=5
# 连接池中最大的活跃连接数
maxActive=10
maxWait=3000
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
public class test
public static void main(String[] args) throws Exception
Properties properties = new Properties();
properties.load(new FileInputStream("D:\\\\Codes\\\\IdeaProjects\\\\test\\\\src\\\\druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection connection = dataSource.getConnection();
System.out.println(connection);
4.JDBC 练习
4.1 新建表并填入数据
drop table if exists tb_brand;
create table tb_brand(
id int primary key auto_increment,
brand_name varchar(20),
company_name varchar(20),
ordered int,
description varchar(100),
status int
);
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠','三只松鼠股份有限公司',5,'好吃不上火',0),
('华为','华为技术有限公司',100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界',1),
('小米','小米科技有限公司',50, 'are you ok', 1);
SELECT * FROM tb_brand;
4.2 实体类 Brand
public class Brand
private Integer id;
private String brand_name;
private String company_name;
private Integer ordered;
private String description;
private Integer status;
public Integer getId()
return id;
public void setId(Integer id)
this.id = id;
public String getBrand_name()
return brand_name;
public void setBrand_name(String brand_name)
this.brand_name = brand_name;
public String getCompany_name()
return company_name;
public void setCompany_name(String company_name)
以上是关于javaweb-数据库的主要内容,如果未能解决你的问题,请参考以下文章