分享

Java数据库基本操作

 Ethan的博客 2010-12-06
Java数据库基本操作 一.SQLServer2000的数据库连接 注: 采用直连数据库,首先应该在工程中导入链接数据库所需要的 3个jar包,如果是SQLServer2005的数据库应该导入相应的2005 的jar包; 1.驱动 string dirver="com.microsoft.jdbc.sqlserver.SQLServerDriver"; 2.url地址 string url ="jdbc:microsoft:sqlserver://localhost:1433;databasename=North"; 3.连接数据库的方法getConn() public Connection getConn() { //加载驱动 try { Class.forName(this.driver); //获取数据库连接 this.conn=DriverManager.getConnection(url,"sa","密码"); } catch (Exception e) { e.printStackTrace(); } return this.conn; } 二.数据库操作 1.对数据库执行查询的方法executeQuery() //此方法返回结果集,返回类型为ResultSet; public ResultSet executeQuery(String sql) { getConn(); try{ this.stmt=this.conn.createStatement(); //对数据库执行查询时用stmt.executeQuery(sql); this.rs=this.stmt.executeQuery(sql); } catch (Exception e) { e.printStackTrace(); } return this.rs; } 2.对数据库执行增删改的方法executeUpdate() //此方法返回True/False,返回值类型boolean public boolean executeUpdate(String sql) { getConn(); try { this.stmt=this.conn.createStatement(); //对数据库执行查询时用stmt.executeUpdate(sql); int i=stmt.executeUpdate(sql); if(i>0){ this.flag=true; } } catch (SQLException e) { e.printStackTrace(); } return flag; } 注: 连接数据库的方法和对数据库操作的方法都在同一个类里面即数据库连接类 Public class connDB{} 三.完整例题 package com.qud.common; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ConnDB { private Connection conn; private Statement stmt; private ResultSet rs; private String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver"; private String url="jdbc:microsoft:sqlserver://localhost:1433;databasename=mydb"; private boolean flag=false; public Connection getConn() { //加载驱动 try { Class.forName(this.driver); //获取数据库连接 this.conn=DriverManager.getConnection(url,"sa",""); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return this.conn; } //公共查询的方法 public ResultSet executeQuery(String sql) { getConn(); try { this.stmt=this.conn.createStatement(); this.rs=this.stmt.executeQuery(sql); } catch (Exception e) { e.printStackTrace(); } return this.rs; } //公共增删改的方法 public boolean executeUpdate(String sql) { getConn(); try { this.stmt=this.conn.createStatement(); int i=stmt.executeUpdate(sql); if(i>0) { this.flag=true; } } catch (SQLException e) { e.printStackTrace(); } return flag; } //关闭数据库 public void close() { try { if(this.rs !=null ) { this.rs.close(); } if(this.stmt != null) { this.stmt.close(); } if(this.conn !=null || !this.conn.isClosed()) { this.conn.close(); } } catch (Exception e) { e.printStackTrace(); } } }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多