连接数据库
下载mysql-connector-java,这里我是看的这个连接mysql-connector-java下载。
下载后并且导入了Idea中的lib文件下。
导入成功后,为了验证可以通过CTRL+n来搜索Driver看看有没有添加进来。
随后在MySQL中创建一个数据库,我这里直接使用的是Navicat,创建了一个java_learn的数据库
在测试类中的测试代码
参考文档元动力
package com;
import org.junit.Test;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestJDBC {
@Test
public void testConnnection1() throws SQLException {
//定义要素
String driverName="com.mysql.cj.jdbc.Driver";
//后面加上时区
String url="jdbc:mysql://127.0.0.1:3306/java_learn?serverTimezone=GMT%2B8";
String username="root";
String password="200625";
//加载驱动
Driver driver= new com.mysql.cj.jdbc.Driver();
//注册驱动
DriverManager.registerDriver(driver);
//获取连接
Connection connection=DriverManager.getConnection(url,username,password);
System.out.println(connection);
}
}
//输出
com.mysql.cj.jdbc.ConnectionImpl@1de76cc7
如上,就说明了数据库连接成功。
也可以更加简洁如下
@Test
public void testConnnection2() throws SQLException {
//定义要素
String driverName="com.mysql.cj.jdbc.Driver";
//后面加上时区
String url="jdbc:mysql://127.0.0.1:3306/java_learn?serverTimezone=GMT%2B8";
String username="root";
String password="200625";
//加载驱动
//new com.mysql.cj.jdbc.Driver();
//jdk会默认创建,也可以去掉下面的代码
Class.forName(driverName);
//获取连接
Connection connection=DriverManager.getConnection(url,username,password);
System.out.println(connection);
}
如果在上面不创建 Class.forName(driverName);这个类的话,会通过SPI自动创建,如下的源码。
其中会自动读取下面文件中的内容
访问数据库
package com.entity;
import java.util.Date;
public class User {
private int id;
private String username;
private String password;
private Date data;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", data=" + data +
'}';
}
}
@Test
public void testStatement2() throws SQLException {
//定义要素
String driverName="com.mysql.cj.jdbc.Driver";
//后面加上时区
String url="jdbc:mysql://127.0.0.1:3306/java_learn?serverTimezone=GMT%2B8";
String username="root";
String password="200625";
//让jvm加载一下就行了
//Class.forName(driverName);
//获取连接
Connection connection= DriverManager.getConnection(url,username,password);
System.out.println(connection);
Statement statement=connection.createStatement();
String sql="select * from user_sql";
ResultSet resultSet = statement.executeQuery(sql);
System.out.println(resultSet);
ArrayList<User> users=new ArrayList<>();
while(resultSet.next()){
User user =new User();
int id = resultSet.getInt(1);
String name =resultSet.getString(2);
String password_sql=resultSet.getString(3);
Date birthday=resultSet.getDate(4);
user.setId(id);
user.setUsername(name);
user.setPassword(password_sql);
user.setData(birthday);
users.add(user);
}
System.out.println(users);
}
优化代码
@Test
public void testStatement3() throws SQLException {
//定义要素
String driverName="com.mysql.cj.jdbc.Driver";
//后面加上时区
String url="jdbc:mysql://127.0.0.1:3306/java_learn?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai";
String username="root";
String password="200625";
String sql="select * from user_sql";
Connection conn=null;
Statement statement =null;
ResultSet resultSet = null;
try{
Driver driver=new com.mysql.cj.jdbc.Driver();
DriverManager.registerDriver(driver);
conn = DriverManager.getConnection(url,username,password);
statement =conn.createStatement();
resultSet=statement.executeQuery(sql);
ArrayList<User> users=new ArrayList<>();
while(resultSet.next()){
User user =new User();
int id = resultSet.getInt(1);
String name =resultSet.getString(2);
String password_sql=resultSet.getString(3);
Date birthday=resultSet.getDate(4);
user.setId(id);
user.setUsername(name);
user.setPassword(password_sql);
user.setData(birthday);
users.add(user);
}
System.out.println(users);
}catch (Exception exception){
exception.printStackTrace();
}finally {
if(conn!=null){
try{
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if(statement!=null){
try{
statement.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if(resultSet!=null){
try{
resultSet.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}
进一步进行优化
对函数进行封装
package com.util;
import java.sql.*;
public class DBUtil {
public static Connection getConnection(){
String url="jdbc:mysql://127.0.0.1:3306/java_learn?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai";
String username="root";
String password="200625";
String sql="select * from user_sql";
Connection conn=null;
Statement statement =null;
ResultSet resultSet = null;
try{
Driver driver = new com.mysql.cj.jdbc.Driver();
DriverManager.registerDriver(driver);
return DriverManager.getConnection(url, username, password);
} catch (Exception exception){
exception.printStackTrace();
}
return null;
}
public static void closeAll(Connection conn,Statement statement,ResultSet resultSet){
if(conn!=null){
try{
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if(statement!=null){
try{
statement.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if(resultSet!=null){
try{
resultSet.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}
@Test
public void testStatement3() throws SQLException {
String sql="select * from user_sql";
Connection conn=null;
Statement statement =null;
ResultSet resultSet = null;
try{
conn = DBUtil.getConnection();
statement =conn.createStatement();
resultSet=statement.executeQuery(sql);
List<User> users=new ArrayList<>();
while(resultSet.next()){
User user =new User();
int id = resultSet.getInt(1);
String name =resultSet.getString(2);
String password_sql=resultSet.getString(3);
Date birthday=resultSet.getDate(4);
user.setId(id);
user.setUsername(name);
user.setPassword(password_sql);
user.setData(birthday);
users.add(user);
}
System.out.println(users);
}catch (Exception exception){
exception.printStackTrace();
}finally {
DBUtil.closeAll(conn,statement,resultSet);
}
}
登录的例子
public static void main(String[] args) {
//输入用户名和密码
Scanner sc= new Scanner(System.in);
System.out.println("请输入用户名:");
String username = sc.nextLine();
System.out.println("请输入密码:");
String password=sc.nextLine();
String sql = "select * from user_sql where name='"+username+"' and password = '"+password+"'";
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
try{
System.out.println("sql------>"+sql);
conn=DBUtil.getConnection();
statement=conn.createStatement();
resultSet=statement.executeQuery(sql);
if(resultSet.next()){
System.out.println("登录成功");
return;
}else {
System.out.println("登录失败");
}
} catch (SQLException throwables) {
System.out.println("登录失败");
throwables.printStackTrace();
}finally {
DBUtil.closeAll(conn,statement,resultSet);
}
}
//输出
请输入用户名:
root
请输入密码:
123
sql------>select * from user_sql where name=‘root’ and password = ‘123’
登录成功
但是其中也有很严重的问题,比如如下的例子:(sql注入,会绕开逻辑)
请输入用户名:
root
请输入密码:
132432423’ or 1='1
sql------>select * from user_sql where name=‘root’ and password = ‘132432423’ or 1=‘1’
登录成功
因为在输入密码的时候后面加上了or 1='1,使得sql代码执行了1=‘1’,这样就会导致结果是true。
PreparedStatement的使用
mysql的预编译:
通常我们发送一条SQL语句给MySQL服务器时,MySQL服务器每次都需要对这条SQL语句进行校验、解析等操作。
但是有很多情况下,我们的一条SQL语句可能需要反复的执行,每次执行可能仅仅是传递的参数不同而已,类似于这样的SQL语句如果每次都需要进行校验、解析等操作,未免太过于浪费性能了,因此产生了SQL语句的预编译。
所谓预编译就是将一些灵活的参数值以占位符?的形式给代替掉,我们把参数值给抽取出来,把SQL语句进行模板化。让MySQL服务器执行相同的SQL语句时,不需要在校验、解析SQL语句上面花费重复的时间。
-- 预编译 --
PREPARE statement from 'SELECT * FROM user_sql WHERE id=? and name=?';
set @id=6;
set @name='root';
execute statement using @id,@name;
查看mysql的通用查询日志。
show VARIABLES like '%general_log%'
发现其中的general_log是OFF,所以这里要增加一个打开的语句。
set GLOBAL general_log=1
如果其中要永久打开通用查询日志,需要在配置文件中进行修改,其中配置文件的路径是C:\ProgramData\MySQL\MySQL Server 8.0
打开其中的my.ini文件,并且将其中的general-log改为1
改为防止sql注入的方法
public static void main(String[] args) {
String sql = "select * from user_sql where id=?";
Connection conn = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
System.out.println("sql------>"+sql);
conn=DBUtil.getConnection();
statement=conn.prepareStatement(sql);
statement.setInt(1,3);
resultSet=statement.executeQuery();
ArrayList<User> users=new ArrayList<>();
while(resultSet.next()){
User user =new User();
int id = resultSet.getInt(1);
String name =resultSet.getString(2);
String password_sql=resultSet.getString(3);
Date birthday=resultSet.getDate(4);
user.setId(id);
user.setUsername(name);
user.setPassword(password_sql);
user.setData(birthday);
users.add(user);
}
System.out.println(users);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.closeAll(conn,statement,resultSet);
}
}
改为登录的代码
public static void main(String[] args) {
String sql = "select * from user_sql where id=? and password =?";
Connection conn = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
System.out.println("sql------>"+sql);
conn=DBUtil.getConnection();
statement=conn.prepareStatement(sql);
Scanner sc=new Scanner(System.in);
System.out.println("请输入账号");
int id_in=sc.nextInt();
System.out.println("请输入密码");
String psw=sc.next();
statement.setInt(1,id_in);
statement.setString(2,psw);
resultSet=statement.executeQuery();
User user =new User();
if(resultSet.next()) {
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
String password_sql = resultSet.getString(3);
Date birthday = resultSet.getDate(4);
user.setId(id);
user.setUsername(name);
user.setPassword(password_sql);
user.setData(birthday);
System.out.println(user);
}
else {
System.out.println("登录失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.closeAll(conn,statement,resultSet);
}
}
注解,其中resultSet.next()的具体解释
boolean java.sql.ResultSet.next() throws SQLException Moves the cursor
forward one row from its current position. A ResultSet cursor is
initially positioned before the first row; the first call to the
method next makes the first row the current row; the second call makes
the second row the current row, and so on. When a call to the next
method returns false, the cursor is positioned after the last row. Any
invocation of a ResultSet method which requires a current row will
result in a SQLException being thrown. If the result set type is
TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver
implementation will return false or throw anSQLException on a
subsequent call to next. If an input stream is open for the current
row, a call to the method next will implicitly close it. A ResultSet
object’s warning chain is cleared when a new row is read.
将指针移动到当前位置的下一行。
ResultSet指针的初始位置位于第一行之前;
第一次调用next()方法将会把第一行设置为当前行;
第二次调用next()方法指针移动到第二行,以此类推。
当对next()方法调用返回 false,说明此时指针位于最后一行之后。所有对 ResultSet需要使用当前行的方法[注:如getString()、getInt()等等]的调用都将导致next()方法抛出 SQLException异常。如果返回的 ResultSet 集合的类型被设置为 TYPE_FORWARD_ONLY ,会在随后对next()方法的调用中返回false 或抛出 SQLException 异常,因不同的数据库提供者的 JDBC 驱动实现而异。
如果为当前行打开了一个输入流,对next()方法的调用将会隐式地关闭它。 当新的一行读入时,ResultSet对象的警告链将被清空。
小结,PreparedStatement 有一下有点:
1、sql的可读性更强,参数更加灵活更加面向对象,不再是简单的拼接字符串。
2、sql会进行预编译,性能高,可以进行重复利用。
3、sql的预编译同样可以防止sql注入。
增删改查
首先创建如下类
创建一个用户类
package com.entity;
import java.sql.Date;
public class User {
private Integer id;
private String username;
private String password;
private Date date;
public User() {
}
public User(Integer id, String username, String password, Date date) {
this.id = id;
this.username = username;
this.password = password;
this.date = date;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", date=" + date +
'}';
}
}
写一个接口
package com.dao;
import com.entity.User;
import java.util.List;
public interface UserDao {
/**
* 插入数据
* @param user 用户实例
* @return 受影响的行数
*/
int insertUser(User user);
/**
* 根据id删除用户
* @param id
* @return 受影响的行数
*/
int deleterUser(int id);
/**
* 修改用户
* @param user 需要修改的用户
* @return 修改后的用户
*/
int updateUser(User user);
/**
* 根据id选择用户
* @param id
* @return 结果
*/
User selectUser(int id);
/**
* 查询所有的用户
* @return 用户列表
*/
List<User> selectAllUsers();
}
对接口中的函数进行重写
package com.dao.impl;
import com.dao.UserDao;
import com.entity.User;
import com.util.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class UserDaoImpl implements UserDao {
@Override
public int insertUser(User user) {
String sql = "insert into user_sql(name,password,birthday) value(?,?,?)";
Connection conn = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
System.out.println("sql------>"+sql);
conn= DBUtil.getConnection();
statement=conn.prepareStatement(sql);
statement.setString(1,user.getUsername());
statement.setString(2,user.getPassword());
statement.setDate(3, new Date(new java.util.Date().getTime()));
int rows=statement.executeUpdate();
return rows;
} catch (SQLException throwables) {
throwables.printStackTrace();
return -1;
}finally {
DBUtil.closeAll(conn,statement,null);
}
}
@Override
public int deleterUser(int id) {
String sql = "delete from user_sql where id=?";
Connection conn = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
System.out.println("sql------>"+sql);
conn= DBUtil.getConnection();
statement=conn.prepareStatement(sql);
statement.setInt(1, id);
int rows=statement.executeUpdate();
return rows;
} catch (SQLException throwables) {
throwables.printStackTrace();
return -1;
}finally {
DBUtil.closeAll(conn,statement,null);
}
}
@Override
public int updateUser(User user) {
String sql = "update user_sql set name =?,password=?,birthday=? where id=? ";
Connection conn = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
System.out.println("sql------>"+sql);
conn= DBUtil.getConnection();
statement=conn.prepareStatement(sql);
statement.setString(1,user.getUsername());
statement.setString(2,user.getPassword());
statement.setDate(3, user.getDate());
statement.setInt(4,user.getId());
return statement.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
return 0;
}finally {
DBUtil.closeAll(conn,statement,null);
}
}
@Override
public User selectUser(int id) {
String sql = "select * from user_sql where id=?";
Connection conn = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
System.out.println("sql------>"+sql);
conn= DBUtil.getConnection();
statement=conn.prepareStatement(sql);
statement.setInt(1,id);
resultSet=statement.executeQuery();
User user =new User();
if(resultSet.next()) {
String name = resultSet.getString("name");
String password_sql = resultSet.getString("password");
Date birthday = resultSet.getDate("birthday");
user.setId(id);
user.setUsername(name);
user.setPassword(password_sql);
user.setDate(birthday);
return user;
}
else {
return null;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}finally {
DBUtil.closeAll(conn,statement,resultSet);
}
}
@Override
public List<User> selectAllUsers() {
String sql = "select id,name,password,birthday from user_sql";
Connection conn = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<User> L=new ArrayList<>();
try{
System.out.println("sql------>"+sql);
conn= DBUtil.getConnection();
statement=conn.prepareStatement(sql);
resultSet=statement.executeQuery();
while (resultSet.next()) {
User user =new User();
int id=resultSet.getInt(1);
String name = resultSet.getString(2);
String password_sql = resultSet.getString(3);
Date birthday = resultSet.getDate(4);
user.setId(id);
user.setUsername(name);
user.setPassword(password_sql);
user.setDate(birthday);
L.add(user);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.closeAll(conn,statement,resultSet);
}
return L;
}
}
增删改查测试
@Test
public void TestInsert() {
User user =new User(null,"lym","123",new Date(new java.util.Date().getTime()));
UserDao userDao=new UserDaoImpl();
userDao.insertUser(user);
}
@Test
public void TestDelete() {
int id=11;//打算删除的用户
UserDao userDao=new UserDaoImpl();
userDao.deleterUser(11);
}
@Test
public void TestUpdate() {
User user =new User(8,"lym","123",new Date(new java.util.Date().getTime()));
UserDao userDao=new UserDaoImpl();
userDao.updateUser(user);
}
@Test
public void TestSelect() {
UserDao userDao=new UserDaoImpl();
User user=userDao.selectUser(3);
System.out.println(user);
}
@Test
public void TestSelectAll() {
UserDao userDao=new UserDaoImpl();
List<User> L=userDao.selectAllUsers();
System.out.println(L);
}