標籤:
1. 擷取資料庫連接和查詢代碼
package connectionmysql;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class ConnectionMysql { //資料庫連接使用者名稱 private String userName = "root"; //資料庫連接密碼 private String pwd = "910214"; //設定資料庫 private String database = "jsp"; //設定jdbc驅動 private String dbDriver = "com.mysql.jdbc.Driver"; //設定資料庫連接URL private String dbConnect = "jdbc:mysql://localhost:3306/"+database; //串連變數 private Connection conn = null; private Statement stmt = null; ResultSet rs = null; /*資料庫驅動註冊*/ public ConnectionMysql() { try{ Class.forName(dbDriver); } catch(Exception ex) { System.out.println("串連失敗: "+ex.getMessage()); } } /*建立資料庫連接及其資料查詢*/ public ResultSet executeQuery(String sql) throws SQLException{ rs = null; try{ conn = DriverManager.getConnection(dbConnect, userName, pwd); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); }catch(Exception ex) { System.out.println("串連失敗: "+ex.getMessage()); }// finally{// //關閉資料庫連接// stmt.close();// conn.close();// } return rs; } /*建立資料庫連接和資料庫查詢*/ public void excuteUpdate(String sql) throws SQLException { stmt = null; try{ //串連資料庫 conn = DriverManager.getConnection(dbConnect, userName, pwd); stmt = conn.createStatement(); stmt.executeUpdate(sql); }catch(Exception ex){ //手動拋出異常 throw new SQLException(ex.getMessage()); }// finally{// stmt.close();// conn.close();// } } /* * 考慮資料庫的效能問題,需要釋放資料庫資源,因此關閉方法 */ //關閉陳述語句 public void CloseStmt() { try{ stmt.close(); }catch(SQLException ex){ System.out.println("關閉資料庫失敗: "+ex.getMessage()); } } //關閉串連 public void CloseConn(){ try{ conn.close(); }catch(SQLException ex){ System.out.println("關閉串連失敗: "+ex.getMessage()); } } }
2.測試代碼
package connectionmysql;import java.sql.ResultSet;import java.sql.SQLException;public class TestMysqlConnection { /** * 運行程式測試 */ public static void main(String[] args) { // TODO Auto-generated method stub ConnectionMysql conMysql = new ConnectionMysql(); //查詢資料庫SQL語句 String sql = "select username,password from userlogin"; try{ //返回查詢結果集 ResultSet rs = conMysql.executeQuery(sql); //列印查詢資料 if(rs.next()){ String username = rs.getString(1); String password = rs.getString(2); System.out.println("使用者名稱: "+username); System.out.println("密 碼 : "+password);// System.out.println(rs.getString(2)); } }catch(SQLException ex){ System.out.println("查詢失敗: "+ex.getMessage()); }finally{ //關閉資料庫連接 conMysql.CloseStmt(); conMysql.CloseConn(); } }}
Java串連MySQl資料庫實現代碼