標籤:localhost 載入 static tco manager resultset mysql資料庫 exe class
本文是對 《JAVA使用JDBC串連MySQL資料庫 二》的改進。
上節使用的是PreparedStatement來執行資料庫語句,但是preparedStatement需要傳遞一個sql語句參數,才能建立。然而,DBHelper類只是起到開啟和關閉資料庫的作用,所以sql語句是要放到應用程式層部分的,而不是放到DBHelper類中。
而statment不需要傳遞一個sql語句參數,就能建立。
修改部分如下:
public class DBHelper { String driver = "com.mysql.jdbc.Driver"; String url= "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "123456"; public Connection conn; //public PreparedStatement pst; public Statement statement; public DBHelper(){ try { // 載入驅動程式 Class.forName(driver); // 連續資料庫 conn = (Connection) DriverManager.getConnection(url, user, password); if(!conn.isClosed()){ System.out.println("Succeeded connecting to the Database!"); } //pst = (PreparedStatement) conn.prepareStatement(sql);//使用prepareStatement來執行SQL語句 statement = (Statement) conn.createStatement();//使用statement來執行SQL語句 } catch (Exception e) { e.printStackTrace(); } } public void close() { try { this.conn.close(); //this.pst.close(); this.statement.close(); } catch (Exception e) { e.printStackTrace(); } }}
public class JDBCTest { public static void main(String[] args){ String sql = "select * from employee";//SQL語句 try{ //DBHelper db = new DBHelper(sql);//建立DBHelper對象 //ResultSet rs = (ResultSet) db.pst.executeQuery();// 返回結果集 DBHelper db = new DBHelper();//建立DBHelper對象 ResultSet rs = (ResultSet) db.statement.executeQuery(sql);// 返回結果集 System.out.println("-----------------"); System.out.println("姓名" +"\t"+ "郵箱" +"\t"+ "日期"); System.out.println("-----------------"); while(rs.next()) { //擷取結果集中的資料 String uname = rs.getString("name"); String uemail = rs.getString("email"); String uhiredate = rs.getString("hiredate"); // 輸出結果 System.out.println(uname +"\t"+ uemail +"\t"+ uhiredate); } rs.close(); db.close();//關閉串連 }catch(SQLException e) { e.printStackTrace(); } }}
JAVA使用JDBC串連MySQL資料庫 二(2)