1. 程式人生 > 實用技巧 >2020暑假專案-車輛派遣管理系統開發記錄#7

2020暑假專案-車輛派遣管理系統開發記錄#7

JDBC

資料庫驅動和JDBC

(1)資料庫驅動是連線資料庫所需,由廠商提供,程式和資料庫驅動打交道
(2)jdbc是一種規範,主要是為了簡化開發人員對資料的統一的操作而提供的一個規範

第一個JDBC程式

package com.ch.jdbc;

import java.sql.*;

public class MyFirstJdbc {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1、載入資料庫驅動
        Class.forName("com.mysql.jdbc.Driver");

        //2、準備連線資訊:url,username,password
        String url = "jdbc:mysql://localhost:3306/mysqlstudy?serverTimezone=GMT&characterEncoding=utf8&useSSL=true";
        String username = "root";
        String password = "root";

        //3、連線資料庫
        Connection conn = DriverManager.getConnection(url, username, password);

        //4、獲取執行SQL語句的物件
        Statement statement = conn.createStatement();

        //5、執行SQL語句
        ResultSet query = statement.executeQuery("select * from student");
        while (query.next()){
            int id = query.getInt("id");
            int score = query.getInt("score");
            String name = query.getString("name");
            System.out.println(id + "------"+ name + "------"+score);
        }

        //6、釋放資源
        query.close();
        statement.close();
        conn.close();
    }

}

URL

String url = "jdbc:mysql://localhost:3306/mysqlstudy?serverTimezone=GMT&characterEncoding=utf8&useSSL=true";

//mysql -- 3306
//jdbc:mysql://localhost:3306/資料庫?引數1&引數2&引數3

//oracle -- 1521
//jdbc:oracle:thin@localhost:1521:sid

//SQLServer -- 1433
//jdbc:sqlserver://localhost:1433;DatabaseName=test

DriverManager

Connection conn = DriverManager.getConnection(url, username, password);

//conn代表資料庫物件
//資料庫可以設定提交
//設定回滾
//設定自動提交
conn.commit();
conn.rollback();
conn.setAutoCommit();

Statement

Statement statement = conn.createStatement();

//statement用來執行SQL的物件,prepareStatement也是用來執行SQL物件的
statement.execute();        //執行任何SQL
statement.executeQuery();   //查詢操作,返回ResultSet
statement.executeUpdate();  //更新、插入、刪除。返回受影響行
statement.executeBatch();   //執行多個SQL

ResultSet

//封裝了所有的查詢結果

query.getObject();  //不知道資料型別的情況下使用
query.getString();
query.getInt();
query.getDate();
……

簡單封裝程式碼實現

jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mysqlstudy?serverTimezone=GMT&characterEncoding=utf8&useSSL=true
username=root
password=root

JdbcUtil

package com.ch.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    //1、獲取配置檔案的資訊並載入驅動
    static {
        try {
            //讀取配置檔案的內容
            InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(in);

            //獲取資料庫相關資訊
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

            //載入驅動
            Class.forName(driver);
        } catch (Exception e) {
        }
    }

    //2、獲取連線
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //3、釋放資源
    public static void close(Connection conn, Statement st, ResultSet rs){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

JdbcTest

package com.ch.jdbc;

import com.ch.util.JdbcUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 增刪查改測試
 */
public class JdbcTest {

    /**
     * 增刪改操作
     * @param sql   填寫需要執行的sql語句
     * @param message   操作是增加還是刪除或者修改
     */
    public static void update(String sql,String message){
        //獲取連線
        Connection conn = JdbcUtil.getConnection();
        //獲取執行SQL的物件
        Statement st = null;
        int result = 0;
        try {
            st = conn.createStatement();
            //執行SQL
            result = st.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (result > 0){
            System.out.println(message+"成功");
        }else{
            System.out.println(message+"失敗");
        }
        //執行完釋放資源
        JdbcUtil.close(conn,st,null);
    }

    /**
     * 查詢操作
     */
    public static void query(){
        //獲取連線
        Connection conn = JdbcUtil.getConnection();
        //獲取執行SQL的物件
        Statement st = null;
        ResultSet rs = null;
        try {
            st = conn.createStatement();
            //執行SQL語句
            String sql = "select * from student";
            rs = st.executeQuery(sql);
            while (rs.next()){
                int id = rs.getInt("id");
                int score = rs.getInt("score");
                String name = rs.getString("name");
                System.out.println(id + "------"+ name + "------"+score);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //執行完釋放資源
        JdbcUtil.close(conn,st,null);
    }

    //測試
    public static void main(String[] args) throws SQLException {
        //新增
        String sql = "insert into student(id,score,`name`) values(10,72,'小四');";
        String message = "插入";
        update(sql,message);

        //修改
        String sql1 = "update student set `name`='張華' where id = 10";
        String message1 = "修改";
        update(sql1,message1);

        //刪除
        String sql2 = "delete from student where id = 10";
        String message2 = "刪除";
        update(sql2,message2);

        //查詢
        query();
    }

}

SQL注入問題

SQL注入就是sql存在漏洞,SQL語句被拼接
public static void doLogin(String uname){
    //獲取連線
    Connection conn = JdbcUtil.getConnection();
    //獲取執行SQL的物件
    Statement st = null;
    ResultSet rs = null;
    try {
        st = conn.createStatement();
        //執行SQL語句
        String sql = "select * from student where `name`='"+uname+"'";
        rs = st.executeQuery(sql);
        while (rs.next()){
            int id = rs.getInt("id");
            int score = rs.getInt("score");
            String name = rs.getString("name");
            System.out.println(id + "------"+ name + "------"+score);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    //執行完釋放資源
    JdbcUtil.close(conn,st,null);
}

防SQL注入改進

使用PrepareStatement 可以防止SQL注入,效率更高(預編譯)
package com.ch.jdbc;

import com.ch.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 防SQL注入問題的一種改進
 */
public class PreJdbcTest {

    public static void main(String[] args) {
        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from student where `name`= ?";
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            pst = conn.prepareStatement(sql);
            pst.setString(1,"張三");

            rs = pst.executeQuery();

            while (rs.next()){
                int id = rs.getInt("id");
                int score = rs.getInt("score");
                String name = rs.getString("name");
                System.out.println(id + "------"+ name + "------"+score);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}