系统所须要的信息都存储在数据库中,例如图书信息、读者信息、借阅信息等,要对这些信息进行操做,就必须链接数据库,为了省去每次操做都要编写链接数据库程序,咱们把链接数据库操做封装到一个类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