Java操作MySQL篇——CURD

JDBC驅動

mysql5.0版本驅動:名稱爲:com.mysql.jdbc.Driver 。連接: mysql-connector-java-5.1.39-bin.jar

mysql8.0版本驅動:名稱爲:com.mysql.cj.jdbc.Driver。連接: mysql- connector-java-8.0.16.jar

兩者的區別:
1 名稱不同;
2 mysql8.0以上按本不需要建立SSL連接,但是需要顯示關閉,需要指明useSSL = false;
3 mysql8.0 需要設置CST
4 注意:mysql5.0版本的驅動被廢棄,推薦使用com.mysql.cj.jdbc.Driver

IDEA連接jdbc方式

1 在projecct 或 model中新建library文件夾(package),將mysql驅動包(jar)放在library中;
在這裏插入圖片描述
2 File-Settings-Project Structure 或者 Ctrl+A+Shift+S
在這裏插入圖片描述
3 添加包引用 ,點擊【+】,選擇JARs or directories
在這裏插入圖片描述

數據庫操作

數據庫連接信息:

/**
 * MySQL 8.0 以上版本 - JDBC 驅動名及數據庫 URL(URL 需要顯示不建立 SSL,還要設置 CST)
 */
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
// url 格式:jdbc:mysql://ipAddress:Port/databaseName?useSSL=false&serverTimezone=UTC
static final String DB_URL = "jdbc:mysql://192.168.42.19:3306/tesjdbc?useSSL=false&serverTimezone=UTC";

static final String USER = "root";
static final String PWD = "sa";

增(Insert)

public static boolean insertUserInfo(ArrayList<TestModel> list) {
        Connection connection = null;
        Statement statement = null;
        PreparedStatement pres = null;
        try {
            Class.forName(JDBC_DRIVER);
            connection = DriverManager.getConnection(DB_URL, USER, PWD);
            if (connection == null) {
                return false;
            }
            statement = connection.createStatement();
            if (statement == null) {
                return false;
            }
            // 設置自動提交 false
            connection.setAutoCommit(false);

            ArrayList<String> sqls = new ArrayList<String>();
            for (TestModel model : list) {
                // 注意 StringBuffer 與 StringBuilder 用法,前者線程安全,後者不是線程安全,適用於單線程
//                StringBuffer sql = new StringBuffer();
//                sql.append("insert into user(name,age) values(");
//                sql.append(model.getName());
//                sql.append(",");
//                sql.append(model.getAge());
//                sql.append(")");
//                sqls.add(sql.toString());

                String sqlString = "insert into user(name,age) values(?,?)";
                // 使用事務
                pres = connection.prepareStatement("insert into user(name,age) values (?,?)");
                pres.setObject(1, model.getName());
                pres.setObject(2, model.getAge());
                pres.execute();
            }
            // commit
            connection.commit();

            // close
            pres.close();
            statement.close();
            connection.close();

        } catch (Exception e) {
            System.out.println(e.getStackTrace());
            try {
                connection.rollback();
                if (pres != null) {
                    pres.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e1) {
                System.out.println(e1.getStackTrace());
            }
        }
        return true;
    }

刪(Delete)

 public static boolean deleteUserInfo(String name) {
    Connection connection = null;
    Statement statement = null;
    try {
        Class.forName(JDBC_DRIVER);
        connection = DriverManager.getConnection(DB_URL, USER, PWD);
        if (connection == null) {
            return false;
        }
        statement = connection.createStatement();
        if (statement == null) {
            return false;
        }
        //boolean success = statement.execute("delete from user where name =" + "'"+name+"'");
        int result = statement.executeUpdate("delete from user where name =" + "'"+name+"'");
        statement.close();
        connection.close();
        return result>0?true:false;

    } catch (Exception e) {
        System.out.println(e.getStackTrace());
        try {
            if (connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
            return false;
        } catch (Exception e1) {
            System.out.println(e1.getStackTrace());
            return false;
        }
    }
}

改(Update)

public static boolean updateUserInfo(TestModel model) {
    Connection connection = null;
    PreparedStatement pres = null;
    try {
        Class.forName(JDBC_DRIVER);
        connection = DriverManager.getConnection(DB_URL,USER,PWD);
        connection.setAutoCommit(false);
        if (connection == null) {
            return false;
        }

        String sql = "update user set user.age=? where user.name=?";
        pres = connection.prepareStatement(sql);
        pres.setObject(1, model.getAge());
        pres.setObject(2, model.getName());

        pres.execute();
        connection.commit();

        pres.close();
        connection.close();
    } catch (Exception e) {
        System.out.println(e.getStackTrace());
        try {
            connection.rollback();
            if (pres != null) {
                pres.close();
            }
            if (connection != null) {
                connection.close();
            }
            System.out.println("更新用戶信息失敗");
            return false;
        } catch (Exception e1) {
            System.out.println("更新用戶信息失敗");
            return false;
        }
    }
    return true;
}

查(Query)

public static List<TestModel> getUserInfo() {
    Connection conn = null;
    Statement state = null;
    ArrayList<TestModel> modelArrayList = null;
    try {
        // register jdbc driver
        Class.forName(JDBC_DRIVER);

        // open database
        System.out.println("連接數據庫...");
        conn = DriverManager.getConnection(DB_URL, USER, PWD);
        if (conn == null) {
            System.out.println("數據庫連接失敗");
            return modelArrayList;
        }

        System.out.println("實例化 Statement 對象");
        // execute query sql
        state = conn.createStatement();
        if (state == null) {
            System.out.println("實例化 Statement 對象失敗");
        }
        String sqlString = "select name,age from user";
        ResultSet set = state.executeQuery(sqlString);
        // reade data to list
        modelArrayList = new ArrayList<TestModel>();
        while (set.next()) {
            TestModel model = new TestModel();
            model.setName(set.getString("name"));
            model.setAge(set.getInt("age"));
            modelArrayList.add(model);
        }
        set.close();
        state.close();
        conn.close();
    } catch (Exception e) {
        System.out.println(e.getStackTrace());
    } finally {
        try {
            if (state != null) {
                state.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
        }
    }
    System.out.println("執行成功!");
    return modelArrayList;
}

Execute,ExecuteUpdate,ExecuteQuery

三者區別如下:
Execute:執行任務sql,返回boolean值,該值表示是否返回一個ResultSet
ExecuteUpdate:執行增、刪、改,返回boolean,該值表示受影響的行數
ExecuteQuery:執行查詢,返回ResultSet結果集

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章