1. 程式人生 > >使用JDBC連線Mysql資料庫

使用JDBC連線Mysql資料庫

完全參考菜鳥教程,做了點必要的修改。

package school_databases;

import java.sql.*;
public class ConnectToMysql {
	//JDBC驅動名及資料庫URL
	static final String JDBC_DRIVER="com.mysql.cj.jdbc.Driver";
	//需要之命是否使用SSL連線和伺服器所在時區
	static final String DB_URL="jdbc:mysql://localhost:3306/university?useSSL=false&serverTimezone=UTC";
	
	//資料庫的使用者名稱與密碼
static final String user="root"; static final String PASS="wcm504534"; public static void main(String[] args) { Connection conn=null; Statement stmt=null; try { //註冊JDBC驅動,Mysql8.0以上版本使用 Class.forName("com.mysql.cj.jdbc.Driver"); //開啟連結 System.out.println("連線資料庫..."); conn=DriverManager.
getConnection(DB_URL,user,PASS); //執行查詢 System.out.println("例項化Statement物件..."); stmt=conn.createStatement(); String sql; sql="SELECT schoolName,city FROM SCHOOL LIMIT 10"; ResultSet rs=stmt.executeQuery(sql); //展開結果集資料庫 while(rs.next()){ String school=rs.getString("schoolName"
); String city=rs.getString("city"); //輸出資料 System.out.printf("school:%-20s",school); System.out.println("city:"+city); } //完成後關閉 rs.close(); stmt.close(); conn.close(); } catch(SQLException se) { //處理JDBC錯誤???? se.printStackTrace(); }catch(Exception e) { //處理Class.forName錯誤 e.printStackTrace(); }finally { //關閉資源 try { if(stmt!=null) stmt.close(); }catch(SQLException se2) { //什麼都不做 } try { if(conn!=null) conn.close(); }catch(SQLException se) { se.printStackTrace(); } } System.out.println("Goodbye!"); } }