zoukankan      html  css  js  c++  java
  • BaseDao代码,用于连接数据库实行增删改查等操作

    在学习JavaWeb时会用到此代码,用于实行增删改查操作
    1
    package com.bdqn.dao; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 /** 10 * 数据库连接与关闭工具类。 11 * @author 北大青鸟 12 */ 13 public class BaseDao { 14 private static String driver = 15 "com.microsoft.sqlserver.jdbc.SQLServerDriver";// 数据库驱动字符串 16 17 private static String url = 18 "jdbc:sqlserver://localhost:3306;DatabaseName=Fruit";// 连接URL字符串 19 private static String user = "sa"; // 数据库用户名 20 private static String password = "bdqn"; // 用户密码 21 22 protected Connection conn; 23 protected PreparedStatement pstmt; 24 protected ResultSet rs; 25 /** 26 * 获取数据库连接对象。 27 */ 28 public Connection getConnection() { 29 Connection conn = null;// 数据连接对象 30 // 获取连接并捕获异常 31 try { 32 Class.forName(driver); 33 conn = DriverManager.getConnection(url, user, password); 34 } catch (Exception e) { 35 e.printStackTrace();// 异常处理 36 } 37 return conn;// 返回连接对象 38 } 39 /** 40 * 关闭数据库连接。 41 * @param conn 数据库连接 42 * @param stmt Statement对象 43 * @param rs 结果集 44 */ 45 public void closeAll(Connection conn, Statement stmt, ResultSet rs) { 46 // 若结果集对象不为空,则关闭 47 if (rs != null) { 48 try { 49 rs.close(); 50 } catch (Exception e) { 51 e.printStackTrace(); 52 } 53 } 54 // 若Statement对象不为空,则关闭 55 if (stmt != null) { 56 try { 57 stmt.close(); 58 } catch (Exception e) { 59 e.printStackTrace(); 60 } 61 } 62 // 若数据库连接对象不为空,则关闭 63 if (conn != null) { 64 try { 65 conn.close(); 66 } catch (Exception e) { 67 e.printStackTrace(); 68 } 69 } 70 } 71 /** 72 * 增、删、改操作 73 * @param sql sql语句 74 * @param prams 参数数组 75 * @return 执行结果 76 */ 77 public int exceuteUpdate(String sql){ 78 79 int result=0; 80 try { 81 conn = getConnection(); 82 Statement stmt = conn.createStatement(); 83 result = stmt.executeUpdate(sql); 84 85 } catch (SQLException e) { 86 // TODO Auto-generated catch block 87 e.printStackTrace(); 88 } 89 90 return result; 91 } 92 /** 93 * 查询操作 94 * @param sql sql语句 95 * @return rs 96 */ 97 public ResultSet exceuteQuery(String sql){ 98 99 try { 100 conn = getConnection(); 101 Statement stmt = conn.createStatement(); 102 rs = stmt.executeQuery(sql); 103 104 } catch (SQLException e) { 105 // TODO Auto-generated catch block 106 e.printStackTrace(); 107 } 108 return rs; 109 } 110 }
  • 相关阅读:
    Android中得到布局文件对象有三种方式
    android中的键值对
    .length()与.length与.size()
    异常处理
    Python操作Excel
    写一个简单的爬虫(博客)
    开发一个登录接口(Mysql)
    常用模块
    内置函数
    装饰器
  • 原文地址:https://www.cnblogs.com/BestFeng/p/BaseDao.html
Copyright © 2011-2022 走看看