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

MySQL連線資料庫查詢

package com.goldmsg.filepusher.jetty;
/**
 * 連線資料庫的工具類,被定義成不可繼承且是私有訪問
 * Created by zhouhaiming on 2016/9/21.
 */
import com.mysql.jdbc.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public final class 
DBUtils { private static String url = "jdbc:mysql://loacalhost:3306/apple"; private static String user = "root"; private static String psw = "1111111"; private static Connection conn; static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace();
throw new RuntimeException(e); } } private DBUtils() { } /** * 獲取資料庫的連線 * @return conn */ public static Connection getConnection() { if(null == conn) { try { conn = DriverManager.getConnection(url, user, psw);
} catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } return conn; } /** * 釋放資源 * @param conn * @param pstmt * @param rs */ public static void closeResources(Connection conn,PreparedStatement pstmt,ResultSet rs) { if(null != rs) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { if(null != pstmt) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { if(null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } } } } } public static class MySQLDemo { // JDBC 驅動名及資料庫 URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/store"; // 資料庫的使用者名稱與密碼,需要根據自己的設定 static final String USER = "root"; static final String PASS = "123456"; public static void main(String[] args) { com.mysql.jdbc.Connection conn = null; Statement stmt = null; try{ // 註冊 JDBC 驅動 Class.forName("com.mysql.jdbc.Driver"); Class.forName(JDBC_DRIVER); // 開啟連結 System.out.println("連線資料庫..."); conn = (com.mysql.jdbc.Connection) DriverManager.getConnection(DB_URL,USER,PASS); // 執行查詢 System.out.println(" 例項化Statement對..."); // stmt = (Statement) conn.createStatement(); stmt = (Statement) conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); String sql; sql = "SELECT * FROM obj_replica_task WHERE task_status =0"; ResultSet rs = stmt.executeQuery(sql); // 展開結果集資料庫 while(rs.next()){ // 通過欄位檢索 String task_id=rs.getString("task_id"); String storage_id=rs.getString("storage_id"); // 輸出資料 System.out.println(task_id); System.out.println(storage_id); } // 完成後關閉 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!"); } } }