当前位置 : 主页 > 编程语言 > java >

这是我自己做的简单JDBC封装,解决了每次连接数据库填写数据库驱动、用户名

来源:互联网 收集:自由互联 发布时间:2021-06-28
这里封装了JDBC所有、删、改、查要用到的方法 package com.weida.dao;/** * 用于数据增、删、改、查 */import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultS
这里封装了JDBC所有、删、改、查要用到的方法
package com.weida.dao;

/**
 * 用于数据增、删、改、查
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.weida.common.StringCommon;

public class ConnectionManager {
	//SQL Server数据连接
//	private static final String CLASSNAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//	private static final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=stuDB";
//	private static final String USER_NAME = "sa";
//	private static final String USER_PASS = "123456";
	
//	//MySql数据库连接
//	private static final String CLASSNAME = "com.mysql.jdbc.Driver";
//	private static final String URL = "jdbc:mysql://localhost:3306/weidadb?characterEncoding=utf-8";
//	private static final String USER_NAME = "root";
//	private static final String USER_PASS = "lyl3580321";
	
	
//	private static final String CLASSNAME = "com.mysql.jdbc.Driver";
//	private static final String URL = "jdbc:mysql://115.238.250.76:3306/sq_xiaoluo?characterEncoding=utf-8";
//	private static final String USER_NAME = "sq_xiaoluo";
//	private static final String USER_PASS = "hiy140";
	
	
	
	/**
	 * 获取连接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		Connection connection = null;
		try {
			Class.forName(StringCommon.jdbc().get("DERVER"));// 加载驱动
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			connection = DriverManager.getConnection(StringCommon.jdbc().get("URL"), StringCommon.jdbc().get("USER"), StringCommon.jdbc().get("PASS"));// 连接数据库
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return connection;
	}

	/**
	 * 根据SQL语句查询并返回结果
	 * 
	 * @param sql
	 *            输入sql查询语句
	 * @return
	 */
	public static ResultSet executeQuery(String sql) {
		Connection connection = null;
		Statement statement = null;
		ResultSet result = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			result = statement.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 根据SQL语句执行增删改
	 * 
	 * @param sql
	 *            增、删、改的sql语句
	 * @return
	 */
	public static boolean executeUpdate(String sql) {
		Connection connection = null;
		Statement statement = null;
		int n = 0;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			n = statement.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll(null, statement, connection);
		}
		if (n > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据SQL语句执行增、删、改
	 * 
	 * @param sql
	 * @param params
	 *            参数数组
	 * @return
	 */
	public static boolean executeUpdate(String sql, Object[] params) {
		Connection connection = null;
		PreparedStatement pstatement = null;
		int n = 0;
		try {
			connection = getConnection();
			pstatement = connection.prepareStatement(sql);
			if (params != null && params.length > 0) {// 判断参数是否有值,如有,则
														// 传给SQL语句中的?
				for (int i = 0; i < params.length; i++) {
					pstatement.setObject(i + 1, params[i]);
				}
			}
			n = pstatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll(null, pstatement, connection);
		}
		if (n > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据SQL语句(必须是聚合函数count(*))查询满足记录的条数
	 * 
	 * @param sql
	 *            带count(*)的sql语句
	 * @return
	 */
	public static int executeCount(String sql) {
		Connection connection = null;
		Statement statement = null;
		ResultSet result = null;
		int n = 0;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			result = statement.executeQuery(sql);
			if (result.next()) {
				n = result.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll(result, statement, connection);
		}
		return n;
	}
	/**
	 * 根据SQL语句(必须是聚合函数count(*))查询满足记录的条数
	 * @param sql  带count(*)的sql语句
	 * @param params
	 * @return
	 */
	public static int executeCount(String sql, Object[] params) {
		Connection connection = null;
		PreparedStatement pstatement = null;
		ResultSet result = null;
		int n = 0;
		try {
			connection = getConnection();
			pstatement = connection.prepareStatement(sql);
			if(params != null && params.length > 0){
				for (int p = 0; p < params.length; p++) {
					pstatement.setObject(p + 1, params[p]);
				}
			}
			result = pstatement.executeQuery();
			if(result.next()){
				n = result.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			closeAll(result, pstatement, connection);
		}
		return n;
	}

	/**
	 * 关闭所有连接的方法
	 * 
	 * @param result
	 * @param statement
	 * @param connection
	 */
	public static void closeAll(ResultSet result, Statement statement, Connection connection) {
		try {
			if (result != null) {
				result.close();
			}
			if (statement != null) {
				statement.close();
			}
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
我把连接数据库的驱动、URL、用户和密码写在了properties文件格式文件里面用逗号(,)隔开。通过IO流读取文件字符串切割封装成Map
DERVER_com.mysql.jdbc.Driver,
URL_jdbc:mysql://localhost:3306/weidadb?characterEncoding=utf-8,
USER_root,
PASS_lyl3580321,
StringCommon类是我写的一个工具类。里面有个是网页html标签过滤和上面的properties文件处理数据库驱动封装成Map。其实我本来是想用 DERVER_com.mysql.jdbc.Driver 这样的xml标签来做点,但是最近在学微信方面的开发没怎么去研究java对XML属性和标签获取的那些技术。以上是我简单的对JDBC封装。虽然没Hibernate 和 Mybatis 强大。但还是有点小自豪的。
package com.weida.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



import com.mysql.jdbc.Driver;

public class StringCommon {

	public static String delHTMLTag(String htmlStr){ 
        String regEx_script="
 
  ]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式 
        String regEx_style="
  
   ]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式 String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式 Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE); Matcher m_script=p_script.matcher(htmlStr); htmlStr=m_script.replaceAll(""); //过滤script标签 Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE); Matcher m_style=p_style.matcher(htmlStr); htmlStr=m_style.replaceAll(""); //过滤style标签 Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE); Matcher m_html=p_html.matcher(htmlStr); htmlStr=m_html.replaceAll(""); //过滤html标签 return htmlStr.trim().replace(" ", "").replace(" ", "").replace("\r\n", ""); //返回文本字符串 } /** * 数据库密码连接 * @return */ public static Map
   
     jdbc(){ URL url = Thread.currentThread().getContextClassLoader().getResource(""); String path = url.getPath(); path = path.substring(1,path.length()); try { BufferedReader buf = new BufferedReader(new FileReader(new File(path+"JDBC.properties"))); String line = ""; String jdbc = ""; while((line = buf.readLine()) != null){ jdbc += line; } String[] str = jdbc.split(","); String[] driver = new String[2]; Map
    
      map = new HashMap
     
      (); for(int i=0;i
      
        map = StringCommon.jdbc(); System.out.println(map.get("USER")); } }
      
     
    
   
  
 
上一篇:HashMap的工作原理
下一篇:学生项目
网友评论