系統所須要的信息都存儲在數據庫中,例如圖書信息、讀者信息、借閱信息等,要對這些信息進行操做,就必須鏈接數據庫,爲了省去每次操做都要編寫鏈接數據庫程序,咱們把鏈接數據庫操做封裝到一個類jdbcfile.java中,在不一樣的模塊中調用這個類就能夠對數據庫進行鏈接,執行相應的數據庫操做 表:圖書信息表、讀者信息表、借閱信息表等。
javascript
DriverManager、Connection、Statement、resultSet
java
import java.sql.*; public class jdbcfile { Connection conn; Statement stmt; int inorupdatevalue=-1; //聲明構造方法,並拋出異常 public jdbcfile() throws Exception { try{ String drivername="jdbc.MySQLDriver"; String dbURL = "jdbc:mysql://localhost:1489/test"; //加載驅動程序 Class.forName(drivername); //建立數據庫鏈接Connection對象 conn=DriverManager.getConnection(dbURL, "chenjinxia", "chenjinxia123"); //建立Statement對象 stmt=conn.createStatement(); }catch(ClassNotFoundException e){ //捕獲異常 throw new Exception("數據庫驅動未找到"+e.getMessage()); }catch(SQLException e){ //捕獲異常 throw new Exception("數據庫未鏈接"+e.getMessage()); } } //定義查詢數據的方法 public synchronized ResultSet executeQuery(String sql) throws Exception{ ResultSet rs=stmt.executeQuery(sql); return rs; } //定義插入數據的方法 public synchronized int insert(String sql) throws Exception { inorupdatevalue=stmt.executeUpdate(sql); return inorupdatevalue; } //定義修改數據的方法 public synchronized int update(String sql) throws Exception { inorupdatevalue=stmt.executeUpdate(sql); return inorupdatevalue; } //定義刪除數據的方法 public synchronized int del(String sql) throws Exception { inorupdatevalue=stmt.executeUpdate(sql); return inorupdatevalue; } //定義關閉數據庫鏈接的方法 public void close() throws Exception{ conn.close(); } }
//建立數據庫鏈接 jdbcfile conn=new jdbcfile(); //產生登陸sql語句 sqlStr="select * from Admin where num='"+str1+"'and password='"+str2+"'"; ResultSet result=conn.executeQuery(sqlStr); if(result.next()){ //彈出對話框提示登陸成功 JOptionPane.showMessageDialog(frame,"登陸成功!"); //打開圖書管理主頁面 bookmain bookmain1=new bookmain(); bookmain1.go(); //關閉登陸窗口 frame.dispose(); //關閉數據庫鏈接 conn.close(); }else{ JOptionPane.showMessageDialog(frame,"用戶名或密碼錯誤"); } }else if(obj.equals(Cancel_btn)){ //點擊取消按鈕 System.exit(0); } }catch(ClassNotFoundException ce){ //捕獲異常 System.out.println("SQLException:"+ce.getMessage()); } catch(SQLException ex){ //捕獲異常 System.out.println(ex); } catch (Exception s) { //捕獲異常 s.printStackTrace(); } } }
創建數據庫,將本身的姓名、學號做爲一條記錄插入。(截圖,需出現本身的學號、姓名)
mysql
在本身創建的數據庫上執行常見SQL語句(截圖)
sql