Java數據庫基本操作一.SQLServer2000的數據庫連接 注: 采用直連數據庫,首先應該在工程中導入鏈接數據庫所需要的 3個(gè)jar包,如果是SQLServer2005的數據庫應該導入相應的2005 的jar包;1.驅動(dòng) string dirver="com.microsoft.jdbc.sqlserver.SQLServerDriver";2.url地址 string url ="jdbc:microsoft:sqlserver://localhost:1433;databasename=North";3.連接數據庫的方法getConn() public Connection getConn() { //加載驅動(dòng) try { Class.forName(this.driver); //獲取數據庫連接 this.conn=DriverManager.getConnection(url,"sa","密碼"); } catch (Exception e) { e.printStackTrace(); } return this.conn; }二.數據庫操作1.對數據庫執行查詢(xún)的方法executeQuery() //此方法返回結果集,返回類(lèi)型為ResultSet; public ResultSet executeQuery(String sql) { getConn(); try{ this.stmt=this.conn.createStatement(); //對數據庫執行查詢(xún)時(shí)用stmt.executeQuery(sql); this.rs=this.stmt.executeQuery(sql); } catch (Exception e) { e.printStackTrace(); } return this.rs; }2.對數據庫執行增刪改的方法executeUpdate() //此方法返回True/False,返回值類(lèi)型boolean public boolean executeUpdate(String sql) { getConn(); try { this.stmt=this.conn.createStatement(); //對數據庫執行查詢(xún)時(shí)用stmt.executeUpdate(sql); int i=stmt.executeUpdate(sql); if(i>0){ this.flag=true; } } catch (SQLException e) { e.printStackTrace(); } return flag; }注: 連接數據庫的方法和對數據庫操作的方法都在同一個(gè)類(lèi)里面即數據庫連接類(lèi) 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(){ //加載驅動(dòng) try { Class.forName(this.driver); //獲取數據庫連接 this.conn=DriverManager.getConnection(url,"sa",""); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return this.conn;}//公共查詢(xún)的方法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;}//關(guān)閉數據庫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(); }}}
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。