1. 程式人生 > 資料庫 >JDBC連線MySQL資料庫查詢操作

JDBC連線MySQL資料庫查詢操作

CREATE TABLE user (id VARCHAR(20), name CHAR(20), age CHAR(2));
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class test3 {
    //定義MySQL的資料庫驅動程式
    public static final String DBDRIVER = "com.mysql.cj.jdbc.Driver";
    //定義MySQL資料庫的連線地址
    public static final String DBURL = "jdbc:mysql://localhost:3306/student?serverTimezone=UTC";
    //MySQL資料庫的連線使用者名稱
    public static final String DBUSER = "root";
    //MySQL資料庫的連線密碼
    public static final String DBPASS = "123456";
    public static void main(String[] args) {
        Connection con = null;
        Statement stmt = null;
        //資料庫插入語句
        String insertSQL = "insert into user (id, name, age) values (3, 'key', 23)";
        //資料庫修改語句
        String alterSQL = "update user SET name='jon' where id=8";
        //資料庫刪除語句
        String deleteSQL = "delete from user where id=5";
        try {
            //載入驅動程式
            Class.forName(DBDRIVER);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            //連線MySQL資料庫時,要寫上連線的使用者名稱和密碼
            con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
            //例項化Statement物件
            stmt = con.createStatement();
            //執行資料庫更新操作
            stmt.executeUpdate(insertSQL);
            stmt.executeUpdate(alterSQL);
            stmt.executeUpdate(deleteSQL);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(con);
        try {
            //關閉操作
            stmt.close();
            //關閉資料庫
            con.close();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

在這裡插入圖片描述