1、jdbc.properties 数据库配置文件
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl jdbc.userName=netrep_txv6 jdbc.password=netrep_txv6_epsoft
2、log4j.properties 文件
log4j.rootCategory=INFO,standard log4j.appender.standard=org.apache.log4j.ConsoleAppender log4j.appender.standard.layout=org.apache.log4j.PatternLayout log4j.appender.standard.layout.ConversionPattern=%-5p\: %d{ISO8601}\: %C{1}[line\:%L}\: %m%n
3、DBConfig.java 读取配置信息
package com.insigma.jdbc.util.dbUtil; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.log4j.Logger; public class DBConfig { private static Logger logger=Logger.getLogger(DBConfig.class); private String driverClassName; private String userName; private String password; private String url; public DBConfig() { //读取db.properties文件 /* Properties props = new Properties(); 代表java命令运行的目录 在java项目下,. java命令的运行目录从项目的根目录开始 在web项目下, . java命令的而运行目录从tomcat/bin目录开始 所以不能使用点. FileInputStream in = new FileInputStream("./src/db.properties"); 使用类路径的读取方式 斜杠表示classpath的根目录 在java项目下,classpath的根目录从bin目录开始 在web项目下,classpath的根目录从WEB-INF/classes目录开始 InputStream in = DBConfig.class.getResourceAsStream("/db.properties");*/ InputStream inStream=DBConfig.class.getResourceAsStream("/jdbc.properties"); Properties properties=new Properties(); try { properties.load(inStream); } catch (IOException e) { logger.error("加载数据库配置文件时发生异常:"+e.getMessage(),e); } this.driverClassName = properties.getProperty("jdbc.driverClassName"); this.userName = properties.getProperty("jdbc.userName"); this.password = properties.getProperty("jdbc.password");; this.url = properties.getProperty("jdbc.url"); } public DBConfig(String driverClassName, String userName, String password, String url) { super(); this.driverClassName = driverClassName; this.userName = userName; this.password = password; this.url = url; } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
4、JDBCUtil.java 封装JDBC访问数据库等信息
package com.insigma.jdbc.util.dbUtil; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; public class JDBCUtil { private static Logger logger=Logger.getLogger(JDBCUtil.class); private static Connection conn=null; private static PreparedStatement pstmt=null; private static ResultSet rs=null; private static String driverClassName=""; private static String url=""; private static String userName=""; private static String password=""; private static void loadConfig(){ DBConfig config=new DBConfig(); driverClassName=config.getDriverClassName(); url=config.getUrl(); userName=config.getUserName(); password=config.getPassword(); } static{ try { loadConfig(); Class.forName(driverClassName); } catch (ClassNotFoundException e) { logger.error("数据库驱动类加载异常:"+e.getMessage(),e); } } public static Connection getConn() throws SQLException{ try{ conn=DriverManager.getConnection(url,userName,password); }catch(RuntimeException re){ logger.error("获取数据库连接异常:"+re.getMessage(),re); throw re; } return conn; } public static PreparedStatement getStmt(String sql) throws SQLException{ try{ pstmt=conn.prepareStatement(sql); }catch(RuntimeException re){ logger.error("获取数据库处理命令异常:"+re.getMessage(),re); throw re; } return pstmt; } public static void setParams(List
5、test_user 测试表
create table test_user ( user_id number primary key, user_name varchar2(20) not null, user_password varchar2(20) not null )
6、UserBean.java 测试实体类
package com.insigma.jdbc.util.test; @SuppressWarnings("serial") public class UserBean implements java.io.Serializable{ private String userId; private String userName; private String userPassword; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public UserBean(String userId, String userName, String userPassword) { super(); this.userId = userId; this.userName = userName; this.userPassword = userPassword; } public UserBean() { super(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((userId == null) ? 0 : userId.hashCode()); result = prime * result + ((userName == null) ? 0 : userName.hashCode()); result = prime * result + ((userPassword == null) ? 0 : userPassword.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UserBean other = (UserBean) obj; if (userId == null) { if (other.userId != null) return false; } else if (!userId.equals(other.userId)) return false; if (userName == null) { if (other.userName != null) return false; } else if (!userName.equals(other.userName)) return false; if (userPassword == null) { if (other.userPassword != null) return false; } else if (!userPassword.equals(other.userPassword)) return false; return true; } @Override public String toString() { return "UserBean [userId=" + userId + ", userName=" + userName + ", userPassword=" + userPassword + "]"; } }
7、JDBCUtilTest 测试类
package com.insigma.jdbc.util.test; import java.beans.IntrospectionException; import java.lang.reflect.InvocationTargetException; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import com.insigma.jdbc.util.dbUtil.JDBCUtil; public class JDBCUtilTest { private static final Logger logger=Logger.getLogger(JDBCUtilTest.class); public static void main(String[] args) { String sql=""; Listparams=null; logger.info("*************************新增开始*****************************"); sql="insert into test_user values(?,?,?)"; params=new ArrayList (); params.add(7777); params.add("剑魔独孤求败"); params.add("SuperMan-Terminator"); testUpdateRecord(sql, params); logger.info("\n"); logger.info("*************************testListHashMap开始********************"); sql="select user_id userId,user_name userName,user_password userPassword from test_user where user_name=?"; params=new ArrayList (); params.add("剑魔独孤求败"); testListHashMap(sql, params); logger.info("\n"); logger.info("*************************testListCommBean开始********************"); sql="select user_id userId,user_name userName,user_password userPassword from test_user where user_password=?"; params=new ArrayList (); params.add("SuperMan-Terminator"); testListCommBean(sql, params); logger.info("\n"); logger.info("*************************testResultRecord开始********************"); sql="select user_id userId,user_name userName,user_password userPassword from test_user where user_id=?"; params=new ArrayList (); params.add(9999); testResultRecord(sql, params); } private static void testResultRecord(String sql, List params) { try { UserBean user=JDBCUtil.getResultBean(UserBean.class, sql, params); if(user!=null){ logger.info("userId="+user.getUserId()+"\t userName="+user.getUserName()+"\t userPassword="+user.getUserPassword()); } } catch (SQLException e) { logger.error("T结果查询失败:"+e.getMessage(),e); } catch (InstantiationException e) { logger.error("T结果查询失败:"+e.getMessage(),e); } catch (IllegalAccessException e) { logger.error("T结果查询失败:"+e.getMessage(),e); } catch (IntrospectionException e) { logger.error("T结果查询失败:"+e.getMessage(),e); } catch (InvocationTargetException e) { logger.error("T结果查询失败:"+e.getMessage(),e); } } private static void testListCommBean(String sql, List params) { try { List listUser=JDBCUtil.getListCommBean(sql, UserBean.class, params); if(listUser!=null&&listUser.size()>0){ for(UserBean user:listUser){ logger.info("userId="+user.getUserId()+"\t userName="+user.getUserName()+"\t userPassword="+user.getUserPassword()); } }else{ logger.info("没有查询到记录"); } } catch (InstantiationException e) { logger.error("List 结果集查询失败:"+e.getMessage(),e); } catch (IllegalAccessException e) { logger.error("List 结果集查询失败:"+e.getMessage(),e); } catch (SQLException e) { logger.error("List 结果集查询失败:"+e.getMessage(),e); } } private static void testUpdateRecord(String sql, List params) { try { int iNum=JDBCUtil.updateRecord(sql, params); logger.info(iNum+"条数据新增成功!"); } catch (SQLException e) { logger.info("数据新增失败:"+e.getMessage(),e); } } private static void testListHashMap(String sql, List params) { try { List >listHashMap=JDBCUtil.getListHashMap(sql, params); if(listHashMap!=null&&listHashMap.size()>0){ for(HashMap hashMap:listHashMap){ String msg="查询记录:\t"; Set keys=hashMap.keySet(); Iterator it=keys.iterator(); while(it.hasNext()){ String key=it.next(); msg+=key+"="+hashMap.get(key)+"\t"; } logger.info(msg); } }else{ logger.info("没有查询到记录"); } } catch (SQLException e) { logger.error("List >结果集查询失败:"+e.getMessage(),e); } } }
8、执行结果:
INFO : 2017-11-17 16:45:09,425: JDBCUtilTest[line:21}: *************************新增开始*****************************
INFO : 2017-11-17 16:45:09,837: JDBCUtilTest[line:111}: 1条数据新增成功!
INFO : 2017-11-17 16:45:09,837: JDBCUtilTest[line:28}:
INFO : 2017-11-17 16:45:09,837: JDBCUtilTest[line:30}: *************************testListHashMap开始********************
INFO : 2017-11-17 16:45:10,435: JDBCUtilTest[line:135}: 查询记录:userpassword=SuperMan-Terminatorusername=剑魔独孤求败userid=9999
INFO : 2017-11-17 16:45:10,435: JDBCUtilTest[line:135}: 查询记录:userpassword=SuperMan-Terminatorusername=剑魔独孤求败userid=8888
INFO : 2017-11-17 16:45:10,435: JDBCUtilTest[line:135}: 查询记录:userpassword=SuperMan-Terminatorusername=剑魔独孤求败userid=7777
INFO : 2017-11-17 16:45:10,436: JDBCUtilTest[line:35}:
INFO : 2017-11-17 16:45:10,436: JDBCUtilTest[line:37}: *************************testListCommBean开始********************
INFO : 2017-11-17 16:45:10,504: JDBCUtilTest[line:88}: userId=9999 userName=剑魔独孤求败 userPassword=SuperMan-Terminator
INFO : 2017-11-17 16:45:10,504: JDBCUtilTest[line:88}: userId=8888 userName=剑魔独孤求败 userPassword=SuperMan-Terminator
INFO : 2017-11-17 16:45:10,504: JDBCUtilTest[line:88}: userId=7777 userName=剑魔独孤求败 userPassword=SuperMan-Terminator
INFO : 2017-11-17 16:45:10,506: JDBCUtilTest[line:42}:
INFO : 2017-11-17 16:45:10,507: JDBCUtilTest[line:44}: *************************testResultRecord开始********************
INFO : 2017-11-17 16:45:10,550: JDBCUtilTest[line:62}: userId=9999 userName=剑魔独孤求败 userPassword=SuperMan-Terminator
9、数据库查询结果
SQL> select * from test_user;
USER_ID USER_NAME USER_PASSWORD
---------- -------------------- --------------------
9999 剑魔独孤求败 SuperMan-Terminator
8888 剑魔独孤求败 SuperMan-Terminator
7777 剑魔独孤求败 SuperMan-Terminator