package com.llt.demo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class DBHelper { public static final String url = "jdbc:mysql://127.0.0.1/test"; // jdbc:mysql://host:port/database name public static final String name = "com.mysql.jdbc.Driver"; public static final String user = "root"; // 數據庫登陸用戶 public static final String password = "123456"; public Connection connection = null; public PreparedStatement pst = null; // 數據庫登陸密碼 public DBHelper(String sql) { try { Class.forName(name);// 指定鏈接類型 connection = DriverManager.getConnection(url, user, password);// 建立鏈接 pst = connection.prepareStatement(sql);// 執行Sql語句 } catch (Exception e) { e.printStackTrace(); } } public void close() { try { this.connection.close(); this.pst.close(); } catch (Exception e) { } } }
package com.llt.demo; import java.sql.ResultSet; public class test { public static String sql = ""; public static DBHelper db = null; public static ResultSet ret = null; public static void main(String[] args) { // TODO Auto-generated method stub String sql = "select * from book"; db = new DBHelper(sql); try { ret = db.pst.executeQuery(); while (ret.next()) { int id = ret.getInt(1); String name = ret.getString(2); System.out.println("id:" + id + ",name:" + name); } // 使用完後將數據庫鏈接關閉 ret.close(); db.close(); } catch (Exception e) { e.printStackTrace(); } } }