jdbc-MySQL8.0連線
阿新 • • 發佈:2020-01-23
package student;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class main {
public static void main(String[] args) throws ClassNotFoundException,SQLException {
//宣告Connection物件
String dbURL = “jdbc:mysql://localhost:3306/runoob?useSSL=false&&allowPublicKeyRetrieval=true&&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC”;
String passWord = “123456”;
Class.forName(“com.mysql.cj.jdbc.Driver”);
Connection connection = DriverManager.getConnection(dbURL,userName,passWord);
Connection con; //驅動程式名 String driver = "com.mysql.cj.jdbc.Driver"; //遍歷查詢結果集 try { //載入驅動程式 Class.forName(driver); //1.getConnection()方法,連線MySQL資料庫!! con = DriverManager.getConnection(dbURL,passWord); if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); //2.建立statement類物件,用來執行SQL語句!! Statement statement = con.createStatement(); //要執行的SQL語句 String sql = "select * from websites"; //3.ResultSet類,用來存放獲取的結果集!! ResultSet rs = statement.executeQuery(sql); System.out.println("--------------------------------------"); System.out.println("執行結果如下所示:"); System.out.println("--------------------------------------"); System.out.println("id" + "\t" + "name" + "\t" + "url" + "\t" +"\t"+"country"); System.out.println("--------------------------------------"); String id = null; String name= null; String url = null; String country = null; while(rs.next()){ //獲取sno這列資料 id = rs.getString("id"); //獲取sname這列資料 name = rs.getString("name"); url = rs.getString("url"); country = rs.getString("country"); //獲取sex這列資料 //輸出結果 System.out.println(id + "\t" + name+"\t"+url+ "\t" + country); } rs.close(); con.close(); } catch(ClassNotFoundException e) { //資料庫驅動類異常處理 System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { //資料庫連線失敗異常處理 e.printStackTrace(); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally{ System.out.println("資料庫資料成功獲取!!"); } }
}