Java連線mysql資料庫程式碼例項程式
阿新 • • 發佈:2020-01-07
這篇文章主要介紹了java連線mysql資料庫程式碼例項程式,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
用java 聯接mysql的例項
在聯接的時候,先確保本機安裝了mysql或者伺服器是安裝了mysql
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MainSql { // JDBC 驅動名及資料庫 URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/chat"; // 資料庫的使用者名稱與密碼,需要根據自己的設定 static final String USER = "root"; static final String PASS = ""; public static void main(String[] args) { // TODO Auto-generated method stub Connection conn = null; Statement stmt = null; try{ Class.forName(JDBC_DRIVER); System.out.println("連結資料庫.."); conn = DriverManager.getConnection(DB_URL,USER,PASS); stmt = conn.createStatement(); String sql = "SELECT * FROM users"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ // 通過欄位檢索 String id = rs.getString("id"); String password = rs.getString("passwd"); // 輸出資料 System.out.println("使用者名稱: " + id); System.out.println("密碼: " + password); } 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!"); } }
這就是mysql聯接的例項程式,這裡我就只貼上了java呼叫mysql,bingqie建立聯接的程式碼,並沒有呼叫到sql語句,其他部分可以在網上找到
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。