Java的JDBC

一.概念

JDBC(Java Database Connectivity)是一种Java编程语言中用于执行SQL语句的API。它提供了一种标准的方法来连接和操作各种类型的关系型数据库,如MySQL、Oracle、MS SQL Server、PostgreSQL等。

二.四个核心对象

  • DriverManager:依据数据库的不同,管理JDBC驱动
  • Connection: 负责连接数据库并担任传送数据的任务
  • Statement: 由 Connection 产生、负责执行SQL语句
  • ResultSet:负责保存Statement执行后所产生的查询结果

三.使用步骤

加载JDBC驱动程序:使用Class.forName()方法加载JDBC驱动程序,例如:
Class.forName(“com.mysql.jdbc.Driver”);

  2 .建立数据库连接:使用DriverManager.getConnection()方法建立数据库连接,例如:

String url = “jdbc:mysql://localhost:3306/test”;
String user = “root”;
String password = “123456”;
Connection conn = DriverManager.getConnection(url, user, password);

  3.创建SQL语句:使用Java的字符串类型创建SQL语句,例如:

String sql = “SELECT * FROM users WHERE id=1”;

  4.执行SQL语句:使用Statement对象或PreparedStatement对象执行SQL语句,例如:

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);

  5.处理结果集:使用ResultSet对象处理SQL语句的结果集,例如:

while(rs.next()){
String name = rs.getString(“name”);
int age = rs.getInt(“age”);
System.out.println(“name=”+name+“,age=”+age);
}

  6.关闭数据库连接:使用Connection对象关闭数据库连接,例如:

conn.close();

四 sql注入

statement执行sql语句的时候会有sql注入的风险,所以推荐使用PreparedStatemen

PreparedStatement ps = con.prepareStatement(sql);
sql语句中的参数可以使用?代替
statement.setInt(索引,值); 索引从1开始的
setXXX  XXX代表数据类型

查询使用executeQuery(); 增删改使用executeUpdate()

​五 工具类

public class JDBCUtils {
private JDBCUtils(){}
private static String url = "jdbc:mysql://localhost:3306/xinzhi666?useUnicode=true&characterEncoding=UTF-8";
private static String user="root";
private static String password="root";
private static String driver="com.mysql.jdbc.Driver";
static {
    try {
        Class.forName(driver);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}
public static Connection getConnection(){
    Connection connection = null;
    try {
        connection = DriverManager.getConnection(url,user,password);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return connection;
}

public static void release(Connection connection, Statement statement, ResultSet resultSet){
    if(resultSet!=null){
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if(connection!=null){
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    if(statement!=null){
        try {
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

六 案例

1 创建jdbc项目,并且导入资料中的jar包
2 创建JDBC工具类
package utils;

import java.sql.*;

/**
 * 工具类 ,也有人叫 BaseDao
 */
public class JDBCUtils {

    private JDBCUtils(){
    }
    public static Connection getConnection(){
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/xinzhi666?useUnicode=true&characterEncoding=UTF-8", "root", "root");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    public static void release(ResultSet rs, Statement statement,Connection connection){

        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void release( Statement statement,Connection connection){

        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


}

3 加密工具

package utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {

    public static String encrypt(String password){
        MessageDigest md = null;
        String s = null;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            s = new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return s;
    }
}

4 实体类
package model;

/**
 * 实体类 ,一般放在model包下, entity
 */
public class User {
    private int id;
    private String username;
    private String password;
    private String name;
    private String phone;
    private String email;

    public User() {
    }

    public User(int id, String username, String password, String name, String phone, String email) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.name = name;
        this.phone = phone;
        this.email = email;
    }

    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 String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

4 dao层代码
package dao;


import model.User;

public interface ILoginDao {

    /**
     * 注册
     * @param user 用户的实体类
     * @return  返回值是一个数字,表示数据库中受影响的行数
     */
    int register(User user);

    /**
     * 登录
     * @param username  用户名
     * @param password  密码
     * @return
     */
    User login(String username, String password);

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    int update(User user,String pw);

    /**
     * 删除用户
     * @param username
     * @param password
     * @return
     */
    int delete(String username, String password);

}

package dao.impl;



import dao.ILoginDao;
import model.User;
import utils.JDBCUtils;
import utils.MD5Utils;

import java.sql.*;

public class LoginDaoImpl implements ILoginDao {


    @Override
    public int register(User user) {
        Connection connection = null;
        PreparedStatement statement = null;
        int i = 0;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "insert into user () values (?,?,?,?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,user.getId());
            statement.setString(2,user.getUsername());
            statement.setString(3, MD5Utils.encrypt(user.getPassword()));
            statement.setString(4,user.getName());
            statement.setString(5,user.getPhone());
            statement.setString(6,user.getEmail());

            i = statement.executeUpdate(); // 数据库中受影响的行数
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //7 释放资源
            JDBCUtils.release(statement,connection);
        }
        return i;
    }

    @Override
    public User login(String username, String password) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String sql = "select id,username,password,name,phone,email from user where username=? and password=?";
        try {
            connection = JDBCUtils.getConnection();
            statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            statement.setString(2,MD5Utils.encrypt(password));
            resultSet = statement.executeQuery();
            while (resultSet.next()){
                User user = new User();
                String id = resultSet.getString("id");
                user.setId(Integer.parseInt(id));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setName(resultSet.getString("name"));
                user.setPhone(resultSet.getString("phone"));
                user.setEmail(resultSet.getString("email"));
                return user;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.release(resultSet,statement,connection);
        }
        return null;
    }

    @Override
    public int update(User user,String pw) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String sql = "update user set name=?,phone=?,password=? where username=? and password=?";
        try {
            connection = JDBCUtils.getConnection();
            statement = connection.prepareStatement(sql);
            statement.setString(1,user.getName());
            statement.setString(2,user.getPhone());
            statement.setString(3,MD5Utils.encrypt(pw));
            statement.setString(4,user.getUsername());
            statement.setString(5,MD5Utils.encrypt(user.getPassword()));
            int i = statement.executeUpdate();
            return i;
        }catch (SQLException throwables) {
                throwables.printStackTrace();
        }finally {
            JDBCUtils.release(resultSet,statement,connection);
        }
        return 0;
    }

    @Override
    public int delete(String username, String password) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String sql = "delete from user where username=? and password=?";
        try {
            connection = JDBCUtils.getConnection();
            statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            statement.setString(2,password);
            int i = statement.executeUpdate();
            return i;
        }catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.release(resultSet,statement,connection);
        }
        return 0;
    }
}

5 测试

import dao.impl.LoginDaoImpl;
import model.User;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

public class Test01 {
    public static void main(String[] args) {
        LoginDaoImpl loginDao = new LoginDaoImpl();
//        int num = loginDao.register(new User(6, "qinyuzhao", "123456", "老韩", "13111223344", "[email protected]"));
//        if(num>0){
//            System.out.println("注册成功");
//        }else {
//            System.out.println("注册失败");
//        }
//        User user = loginDao.login("qinyuzhao", "123456");
//        if(user!=null){
//            System.out.println("登录成功,欢迎"+user.getName()+"回来");
//        }else {
//            System.out.println("登录失败");
//        }
//        int update = loginDao.update(new User(6, "qinyuzhao", "123456", "秦昱照", "12315", "[email protected]"),"root");
//        if(update>0){
//            System.out.println("修改成功");
//        }else {
//            System.out.println("修改失败");
//        }

//        int delete = loginDao.delete("changkaixun", "zhanan");
//        if(delete>0){
//            System.out.println("删除成功");
//        }else {
//            System.out.println("删除失败");
//        }
//        Test01 test01 = new Test01();
//        Scanner scanner = new Scanner(System.in);
//        System.out.println("请输入要加密的字符串:");
//        String str = scanner.next();
//        String encrypt = test01.encrypt(str);
//        System.out.println("加密前:"+str+",加密后的:"+encrypt);

    }

    public String encrypt(String password){
        MessageDigest md = null;
        String s = null;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            s = new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return s;
    }

}

·······

你可能感兴趣的:(JDBC,java)