ConnDB.java
资源名称:Library.rar [点击查看]
上传用户:ycdfsj258
上传日期:2022-08-04
资源大小:1094k
文件大小:2k
源码类别:
图形图象
开发平台:
Java
- package com.core;
- import java.sql.*;
- public class ConnDB {
- public Connection conn=null;
- public ResultSet rs=null;
- public Statement stmt=null;
- /*private String proxool = "org.logicalcobwebs.proxool.ProxoolDriver";
- private String poolname = "proxool.library";*/
- //说明:此处需要配置web.xml文件
- public ConnDB() { //构造方法
- }
- public Connection getConnection() {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- System.out.println("OK1");//连接数据库 如果成功并提示OK1
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_library","root","111");
- System.out.println("OK2");//初始化con 如果成功并提示OK2
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }//异常处理
- return conn;//按发法要求返回个Connection对象
- }
- /*
- *功能:执行查询语句
- */
- public ResultSet executeQuery(String sql) {
- try {
- conn = getConnection();
- stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- rs = stmt.executeQuery(sql);
- }
- catch (SQLException ex) {
- System.err.println(ex.getMessage());
- }
- return rs;
- }
- /*
- *功能:执行更新操作
- */
- public int executeUpdate(String sql) {
- int result = 0;
- try {
- conn = getConnection();
- stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- result = stmt.executeUpdate(sql);
- }
- catch (SQLException ex) {
- result = 0;
- }
- try {
- stmt.close();
- }
- catch (SQLException ex1) {
- }
- return result;
- }
- /*
- *功能:关闭数据库的连接
- */
- public void close() {
- try {
- if (rs != null) {
- rs.close();
- }
- }
- catch (Exception e) {
- e.printStackTrace(System.err);
- }
- try {
- if (stmt != null) {
- stmt.close();
- }
- }
- catch (Exception e) {
- e.printStackTrace(System.err);
- }
- try {
- if (conn != null) {
- conn.close();
- }
- }
- catch (Exception e) {
- e.printStackTrace(System.err);
- }
- }
- }