DOCX

DbHelper

By Cindy Rose,2014-06-25 11:31
11 views 0
DbHelper

package net.pcedu.test;

import java.sql.*;

public class DbHelper {

     private Connection conn;

     private Statement stmt;

     private ResultSet rs;

     private String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";

     private String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=bookdb";

     private String username="sa";

     private String pwd="000";

     /**

     * 获得连接

     * @return

     */

     public Connection getConnection()

     {

     try {

     Class.forName(driver);

     conn=DriverManager.getConnection(uri,username,pwd);

     conn.setAutoCommit(false);

     } catch (ClassNotFoundException e) {

     e.printStackTrace();

     } catch (SQLException e) {

     e.printStackTrace();

     }

     return conn;

     }

     /**

     * 获得会话

     * @return

     */

     public Statement getStatement()

     {

     try {

     if(conn==null||conn.isClosed())

     {

     conn=getConnection();

     }

     stmt=conn.createStatement();

     } catch (SQLException e) {

     e.printStackTrace();

     }

     return stmt;

     }

     /**

     * 获得结果集

     * @param sql

     * @return

     */

     public ResultSet doQuery(String sql)

     {

     try {

     stmt=getStatement();

     rs=stmt.executeQuery(sql);

     } catch (SQLException e) {

     e.printStackTrace();

     }

     return rs;

     }

     /**

     * 执行更新操作

     * @param sql

     */

     public void doUpdate(String sql)

     {

     try {

     if(stmt==null)

     {

     stmt=getStatement();

     stmt.executeUpdate(sql);

     conn.commit();//提交事务

     }

     } catch (SQLException e) {

     e.printStackTrace();

     try {

     conn.rollback();//回滚事务

     } catch (SQLException e1) {

     e1.printStackTrace();

     }

     }finally{//关闭资源

     Close();

     }

     }

     /**

     * 关闭资源

     */

     public void Close()

     {

     try {

     if(rs!=null){rs.close();}//注意对象关闭了,但并不为空

     if(stmt!=null){stmt.close();}

     if(conn!=null||!conn.isClosed()){conn.close();}

     } catch (SQLException e) {

     e.printStackTrace();

     }

     }

}

Report this document

For any questions or suggestions please email
cust-service@docsford.com