官網下載頁面 → 選 Platform Independent → ZIP/TAR.GZ → 解壓取 mysql-connector-java-
MySQL 5.7)jdbc:mysql://:/ DB Browser 中新建連線 → 選剛建立的驅動 → 輸入帳密 → Test Connection → 成功綠勾
WEB-INF/libpackage com.bipt.db;
import java.sql.*;
public class DBCon {
public static Connection conn = null;
public static Statement stmt = null;
public static ResultSet rs = null;
public void getCon() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost/btestdemo?user=root&password=bipt");
}
public void closeCon(Connection conn) throws SQLException {
if (conn != null) conn.close();
}
public static void main(String[] args) {
DBCon dbc = new DBCon();
try {
dbc.getCon();
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM user");
while (rs.next()) {
System.out.println(rs.getInt("USERID"));
System.out.println(rs.getString("USERNAME"));
System.out.println(rs.getString("USERPASSWORD"));
System.out.println();
}
System.out.println("mysql測試成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (Exception ignored) {}
try { if (stmt != null) stmt.close(); } catch (Exception ignored) {}
try { if (conn != null) conn.close(); } catch (Exception ignored) {}
}
}
}
CREATE TABLE `user` ( `USERID` INT(11) NOT NULL AUTO_INCREMENT, `USERNAME` VARCHAR(30) NOT NULL DEFAULT '', `USERPASSWORD` VARCHAR(30) DEFAULT '', PRIMARY KEY (`USERID`) ) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
com.mysql.jdbc.Driver,8.0+ 用 com.mysql.cj.jdbc.DriveruseUnicode=true&characterEncoding=UTF-8 解決中文亂碼try-with-resources(Java 7+)記錄每一步截圖與代碼,建立個人知識庫,下次配置不再踩坑。