• JavaWeb项目的数据库访问简单基础类


    package com.etc.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    /** 数据库访问基础类 */
    public class BaseDao {
    	//String driver="com.mysql.cj.jdbc.Driver"; //mysql8	
    	//String url="jdbc:mysql://localhost:3306/iotdemo?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";//mysql8
    	String driver="com.mysql.jdbc.Driver"; //mysql5
    	String url="jdbc:mysql://localhost:3306/myjob";//mysql5 
    	String user="root";
    	String password="root";
    	
    	/**
    	 * 获得数据库连接
    	 * 
    	 * @return 数据库连接对象
    	 */
    	public Connection getConnection() {
    		Connection conn = null;// 数据库连接对象
    		if (conn == null) {
    			try {
    				Class.forName(driver);// 加载驱动
    				conn = DriverManager.getConnection(url, user, password);// 建立连接
    			} catch (ClassNotFoundException e) {
    				e.printStackTrace();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    		return conn;
    	}
    
    	/**
    	 * 关闭资源
    	 */
    	public void closeAll(ResultSet rs, PreparedStatement ps, Connection conn) {
    		try {
    			if (rs != null) {
    				rs.close();
    			}
    			if (ps != null) {
    				ps.close();
    			}
    			if (conn != null) {
    				conn.close();
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    	}
    
    	/**
    	 * 增删改通用方法
    	 * 
    	 * @param sql
    	 *            执行增删改的SQL语句
    	 * @param args
    	 *            参数数组
    	 * @return 受影响行数
    	 */
    	public int executeUpdate(String sql, Object... args) {
    		int result = -1;
    		PreparedStatement ps = null;// 预编译对象
    		Connection conn = this.getConnection();
    		try {
    			ps = conn.prepareStatement(sql);
    			if (args != null) {
    				for (int i = 0; i < args.length; i++) {
    					ps.setObject(i + 1, args[i]);
    				}
    			}
    			result = ps.executeUpdate();// 执行增删改
    		} catch (SQLException e) {
    			e.printStackTrace();
    		} finally {
    			this.closeAll(null, ps, conn);
    		}
    		return result;
    	}
    }
    

      

  • 相关阅读:
    Yahoo 14条 雅虎十四条 优化原则【转】
    从HTML1到HTML5,回首HTML发展历史【转】
    HTML的发展历史【转】
    jquery中prop()方法和attr()方法的区别【转】
    一个文献综述的写法
    ammunition用法
    混了SQL连接就运行这个
    cruel用法
    ball up用法
    episode用法
  • 原文地址:https://www.cnblogs.com/rask/p/13187936.html
Copyright © 2020-2023  润新知