Chinaunix首页 | 论坛 | 博客
  • 博客访问: 874946
  • 博文数量: 372
  • 博客积分: 10063
  • 博客等级: 中将
  • 技术积分: 4220
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 11:36
文章分类

全部博文(372)

文章存档

2012年(372)

分类: 虚拟化

2012-03-20 20:49:23

一、写前唠叨

最近写了一个关于将对象通过log4j的形式保存到数据库的例子,因对这个log4j正在入门,所以做之前查过很多资料,不过网上的信息比较简单,如下:

1.所有信息几乎全部在配置文件中进行获取,如:数据库相关的连接、用户名、密码、sql语句;日志相关的appender、输出、格式化、参数;

2.写到数据库中的仅是一个字符串而不是一个对象,如:将一个对象本身以及它的各个数据作为一条记录存到数据库

3.代码的灵活性较低,如:只能存比较简单的数据类型,如保存一个对象及属性的话,就不太容易做了。

当然,网上的这些资料当然是为了最基础的入门而做的,因此简单了些,但也不乏比较深奥的资料,比如穿件连接池,考虑缓存等等。。

二、我的做法

1.通过继承JDBCAppender实现日志的写入的

2.通过JDBC连接数据库(也可通过HIBERNATE)

3.数据库和log4j的基本信息配置到properties中,但数据库可以自由选择多种数据库(在配置文件中配置即可)

4.将对象的属性存到库中

三、项目例子

1.项目结构图:见附件,项目结构图.png

2. 数据库:MYSQL 库名:LOG4J 表名:LogMessage/StudentMessage

表结构请看附件:LogMessage.png/StudentMessage.png

3.代码及说明

log4j.properties :分别输出指定为:控制台、文件(log.log)、数据库

Java代码 复制代码 收藏代码
  1. log4j.rootLogger=INFO,appender1,appender2,DATABASE
  2. # console
  3. log4j.appender.appender1=org.apache.log4j.ConsoleAppender
  4. log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.appender1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n
  6. # file
  7. log4j.appender.appender2=org.apache.log4j.FileAppender
  8. log4j.appender.appender2.File=log.log
  9. log4j.appender.appender2.layout=org.apache.log4j.PatternLayout
  10. log4j.appender.appender2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n
  11. #mysql dbappender test
  12. log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver
  13. log4j.appender.DATABASE.URL=jdbc:mysql://127.0.0.1:3306/LOG4J
  14. log4j.appender.DATABASE.username=root
  15. log4j.appender.DATABASE.password=root
  16. log4j.appender.DATABASE=control.DbAppender
  17. log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout
  18. log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n %L
log4j.rootLogger=INFO,appender1,appender2,DATABASE # console log4j.appender.appender1=org.apache.log4j.ConsoleAppender log4j.appender.appender1.layout=org.apache.log4j.PatternLayout log4j.appender.appender1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n # file log4j.appender.appender2=org.apache.log4j.FileAppender log4j.appender.appender2.File=log.log log4j.appender.appender2.layout=org.apache.log4j.PatternLayout log4j.appender.appender2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n #mysql dbappender test log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver log4j.appender.DATABASE.URL=jdbc:mysql://127.0.0.1:3306/LOG4J log4j.appender.DATABASE.username=root log4j.appender.DATABASE.password=root log4j.appender.DATABASE=control.DbAppender log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n %L

Conorl包——DbAppender.java :日志提交中转站,提取日志信息,处理后进行数据库操作插入对应的表中

Java代码 复制代码 收藏代码
  1. package control;
  2. import java.sql.Connection;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.Hashtable;
  7. import java.util.Iterator;
  8. import java.util.Map;
  9. import org.apache.log4j.jdbc.JDBCAppender;
  10. import org.apache.log4j.spi.ErrorCode;
  11. import org.apache.log4j.spi.LoggingEvent;
  12. import bean.HashMapping;
  13. import bean.Students;
  14. import bean.UserBean;
  15. import dao.JdbcUtils;
  16. import dao.StudentsUtil;
  17. import dao.UserUtil;
  18. public class DbAppender extends JDBCAppender {
  19. protected void closeConnection(Connection con) {
  20. // TODO Auto-generated method stub
  21. // super.closeConnection(con);
  22. JdbcUtils.close(con);
  23. }
  24. @Override
  25. protected void execute(String sql) throws SQLException {
  26. // TODO Auto-generated method stub
  27. // super.execute(arg0);
  28. int flag = 0;
  29. int end = sql.lastIndexOf(")");
  30. String sqls = sql.substring(0, end + 1);
  31. String beanname = sql.substring(end + 1);
  32. if (beanname.equals("UserBean")) {
  33. flag = UserUtil.insertUser(sqls);
  34. } else if (beanname.equals("Students")) {
  35. flag = StudentsUtil.insertStudent(sqls);
  36. }
  37. System.out.println(flag == 0 ? "insert fail!" : "insert successful!");
  38. }
  39. @Override
  40. protected Connection getConnection() throws SQLException {
  41. // TODO Auto-generated method stub
  42. // return super.getConnection();
  43. if (connection == null) {
  44. connection = JdbcUtils.getConnection();
  45. }
  46. return connection;
  47. }
  48. @Override
  49. protected String getLogStatement(LoggingEvent event) {
  50. // TODO Auto-generated method stub
  51. // return super.getLogStatement(event);
  52. StringBuffer sbuf = new StringBuffer();
  53. Hashtable hm = (Hashtable) event.getMessage();
  54. String sql = null;
  55. if ((hm.get("beanname")).equals("UserBean")) {
  56. sbuf.append(UserUtil.insertSql());
  57. sql = sbuf.toString();
  58. int end = sql.lastIndexOf("(");
  59. sql = sql.substring(0, end) + "('" + hm.get(HashMapping.USER_TIME)
  60. + "','" + event.getMessage() + "','"
  61. + hm.get(HashMapping.USER_USERNAME) + "','"
  62. + hm.get(HashMapping.USER_PASSWORD) + "')";
  63. System.out.println(sql);
  64. return sql + hm.get("beanname");
  65. } else if ((hm.get("beanname")).equals("Students")) {
  66. sbuf.append(StudentsUtil.insertSql());
  67. sql = sbuf.toString();
  68. int end = sql.lastIndexOf("(");
  69. sql = sql.substring(0, end)
  70. + "('"
  71. + hm.get(HashMapping.STUDENT_NAME)
  72. + "','"
  73. + hm.get(HashMapping.STUDENT_AGE)
  74. + "','"
  75. + (((Integer) (hm.get(HashMapping.STUDENT_***))) == 1 ? "F"
  76. : "M") + "','" + hm.get(HashMapping.STUDENT_TIME)
  77. + "')";
  78. System.out.println(sql);
  79. return sql + hm.get("beanname");
  80. }
  81. return sql;
  82. }
  83. }
package control; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import org.apache.log4j.jdbc.JDBCAppender; import org.apache.log4j.spi.ErrorCode; import org.apache.log4j.spi.LoggingEvent; import bean.HashMapping; import bean.Students; import bean.UserBean; import dao.JdbcUtils; import dao.StudentsUtil; import dao.UserUtil; public class DbAppender extends JDBCAppender { protected void closeConnection(Connection con) { // TODO Auto-generated method stub // super.closeConnection(con); JdbcUtils.close(con); } @Override protected void execute(String sql) throws SQLException { // TODO Auto-generated method stub // super.execute(arg0); int flag = 0; int end = sql.lastIndexOf(")"); String sqls = sql.substring(0, end + 1); String beanname = sql.substring(end + 1); if (beanname.equals("UserBean")) { flag = UserUtil.insertUser(sqls); } else if (beanname.equals("Students")) { flag = StudentsUtil.insertStudent(sqls); } System.out.println(flag == 0 ? "insert fail!" : "insert successful!"); } @Override protected Connection getConnection() throws SQLException { // TODO Auto-generated method stub // return super.getConnection(); if (connection == null) { connection = JdbcUtils.getConnection(); } return connection; } @Override protected String getLogStatement(LoggingEvent event) { // TODO Auto-generated method stub // return super.getLogStatement(event); StringBuffer sbuf = new StringBuffer(); Hashtable hm = (Hashtable) event.getMessage(); String sql = null; if ((hm.get("beanname")).equals("UserBean")) { sbuf.append(UserUtil.insertSql()); sql = sbuf.toString(); int end = sql.lastIndexOf("("); sql = sql.substring(0, end) + "('" + hm.get(HashMapping.USER_TIME) + "','" + event.getMessage() + "','" + hm.get(HashMapping.USER_USERNAME) + "','" + hm.get(HashMapping.USER_PASSWORD) + "')"; System.out.println(sql); return sql + hm.get("beanname"); } else if ((hm.get("beanname")).equals("Students")) { sbuf.append(StudentsUtil.insertSql()); sql = sbuf.toString(); int end = sql.lastIndexOf("("); sql = sql.substring(0, end) + "('" + hm.get(HashMapping.STUDENT_NAME) + "','" + hm.get(HashMapping.STUDENT_AGE) + "','" + (((Integer) (hm.get(HashMapping.STUDENT_***))) == 1 ? "F" : "M") + "','" + hm.get(HashMapping.STUDENT_TIME) + "')"; System.out.println(sql); return sql + hm.get("beanname"); } return sql; } }

Bean包中的类——HashMapping.java :将属性设置成常量(即键-值对中的键),便于代码中进行键值对的读取。

Java代码 复制代码 收藏代码
  1. package bean;
  2. public class HashMapping {
  3. public static final String USER_USERNAME = "username";
  4. public static final String USER_PASSWORD = "password";
  5. public static final String USER_TIME = "time";
  6. public static final String STUDENT_NAME = "name";
  7. public static final String STUDENT_AGE = "age";
  8. public static final String STUDENT_*** = "***";
  9. public static final String STUDENT_TIME = "time";
  10. }
package bean; public class HashMapping { public static final String USER_USERNAME = "username"; public static final String USER_PASSWORD = "password"; public static final String USER_TIME = "time"; public static final String STUDENT_NAME = "name"; public static final String STUDENT_AGE = "age"; public static final String STUDENT_*** = "***"; public static final String STUDENT_TIME = "time"; }

Bean包中的类——UserBean.java/Students.java: 对LogMessage/studentMessage表及此对象持久化

Java代码 复制代码 收藏代码
  1. package bean;
  2. public class Students {
  3. private String name;
  4. private int age;
  5. private int ***;
  6. private String time;
  7. public String getTime() {
  8. return time;
  9. }
  10. public void setTime(String time) {
  11. this.time = time;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public int getAge() {
  20. return age;
  21. }
  22. public void setAge(int age) {
  23. this.age = age;
  24. }
  25. public int get***() {
  26. return ***;
  27. }
  28. public void set***(int ***) {
  29. this.*** = ***;
  30. }
  31. }
  32. //===============================================
  33. package bean;
  34. import java.sql.Date;
  35. public class UserBean {
  36. private String username;
  37. private String password;
  38. private String Time;
  39. private String Note;
  40. public String getTime() {
  41. return Time;
  42. }
  43. public void setTime(String time) {
  44. Time = time;
  45. }
  46. public String getNote() {
  47. return Note;
  48. }
  49. public void setNote(String note) {
  50. Note = note;
  51. }
  52. public String getUsername() {
  53. return username;
  54. }
  55. public void setUsername(String username) {
  56. this.username = username;
  57. }
  58. public String getPassword() {
  59. return password;
  60. }
  61. public void setPassword(String password) {
  62. this.password = password;
  63. }
  64. }
package bean; public class Students { private String name; private int age; private int ***; private String time; public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int get***() { return ***; } public void set***(int ***) { this.*** = ***; } } //=============================================== package bean; import java.sql.Date; public class UserBean { private String username; private String password; private String Time; private String Note; public String getTime() { return Time; } public void setTime(String time) { Time = time; } public String getNote() { return Note; } public void setNote(String note) { Note = note; } 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; } }

Dao中的包——GetObject.java: 将对象放到hashtable中并发送到dbappender中

Java代码 复制代码 收藏代码
  1. package dao;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4. import java.text.SimpleDateFormat;
  5. import java.util.Date;
  6. import java.util.Hashtable;
  7. import org.apache.log4j.Logger;
  8. import org.apache.log4j.PropertyConfigurator;
  9. import test.Test;
  10. import bean.Students;
  11. import bean.UserBean;
  12. public class GetObject {
  13. private Logger logger = Logger.getLogger(GetObject.class);
  14. private UserBean ub;
  15. private Students st;
  16. private SimpleDateFormat sf;
  17. // 保存对象
  18. public UserBean insertInfo(String username, String password) {
  19. ub = new UserBean();
  20. ub.setUsername(username);
  21. ub.setPassword(password);
  22. return ub;
  23. }
  24. public Logger getLogger() {
  25. return logger;
  26. }
  27. public void setLogger(Logger logger) {
  28. this.logger = logger;
  29. }
  30. public UserBean getUb() {
  31. return ub;
  32. }
  33. public void setUb(UserBean ub) {
  34. this.ub = ub;
  35. }
  36. public Students getSt() {
  37. return st;
  38. }
  39. public void setSt(Students st) {
  40. this.st = st;
  41. }
  42. public SimpleDateFormat getSf() {
  43. return sf;
  44. }
  45. public void setSf(SimpleDateFormat sf) {
  46. this.sf = sf;
  47. }
  48. public Students insertInfo(String name, int age, int ***) {
  49. st = new Students();
  50. st.setName(name);
  51. st.setAge(age);
  52. st.set***(***);
  53. return st;
  54. }
  55. // bean key-value
  56. public void getMethod(Object obj) {
  57. sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
  58. PropertyConfigurator.configure("log4j.properties");
  59. Hashtable ht = new Hashtable();
  60. ht.clear();
  61. if (obj instanceof UserBean) {
  62. ht.put("username", ub.getUsername());
  63. ht.put("password", ub.getPassword());
  64. ht.put("time", sf.format(new Date()));
  65. ht.put("beanname", "UserBean");
  66. } else if (obj instanceof Students) {
  67. ht.put("name", st.getName());
  68. ht.put("age", st.getAge());
  69. ht.put("***", st.get***());
  70. ht.put("time", sf.format(new Date()));
  71. ht.put("beanname","Students");
  72. }
  73. logger.info(ht);
  74. }
  75. }
package dao; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Hashtable; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import test.Test; import bean.Students; import bean.UserBean; public class GetObject { private Logger logger = Logger.getLogger(GetObject.class); private UserBean ub; private Students st; private SimpleDateFormat sf; // 保存对象 public UserBean insertInfo(String username, String password) { ub = new UserBean(); ub.setUsername(username); ub.setPassword(password); return ub; } public Logger getLogger() { return logger; } public void setLogger(Logger logger) { this.logger = logger; } public UserBean getUb() { return ub; } public void setUb(UserBean ub) { this.ub = ub; } public Students getSt() { return st; } public void setSt(Students st) { this.st = st; } public SimpleDateFormat getSf() { return sf; } public void setSf(SimpleDateFormat sf) { this.sf = sf; } public Students insertInfo(String name, int age, int ***) { st = new Students(); st.setName(name); st.setAge(age); st.set***(***); return st; } // bean key-value public void getMethod(Object obj) { sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); PropertyConfigurator.configure("log4j.properties"); Hashtable ht = new Hashtable(); ht.clear(); if (obj instanceof UserBean) { ht.put("username", ub.getUsername()); ht.put("password", ub.getPassword()); ht.put("time", sf.format(new Date())); ht.put("beanname", "UserBean"); } else if (obj instanceof Students) { ht.put("name", st.getName()); ht.put("age", st.getAge()); ht.put("***", st.get***()); ht.put("time", sf.format(new Date())); ht.put("beanname","Students"); } logger.info(ht); } }

Dao中的包——JdbcUtils.java: 数据库的动态链接

Java代码 复制代码 收藏代码
  1. package dao;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9. import java.util.Iterator;
  10. import java.util.Properties;
  11. import java.util.Set;
  12. public final class JdbcUtils {
  13. //
  14. private static String url = null;
  15. private static String driver = null;
  16. private static String username = null;
  17. private static String password = null;
  18. private JdbcUtils() {
  19. }
  20. static{
  21. try {
  22. getProperties();
  23. Class.forName(driver);
  24. } catch (ClassNotFoundException e) {
  25. // TODO Auto-generated catch block
  26. e.printStackTrace();
  27. }
  28. }
  29. public static Connection getConnection() throws SQLException {
  30. return DriverManager.getConnection(url, username, password);
  31. }
  32. public static void close(Connection conn) {
  33. try {
  34. if (conn != null)
  35. conn.close();
  36. } catch (SQLException e) {
  37. // TODO Auto-generated catch block
  38. e.printStackTrace();
  39. }
  40. }
  41. public static void getProperties() {
  42. Properties props = new Properties();
  43. FileInputStream istream = null;
  44. try {
  45. istream = new FileInputStream("log4j.properties");
  46. props.load(istream);
  47. Set s = props.keySet();
  48. Iterator it = s.iterator();
  49. while (it.hasNext()) {
  50. String id = (String) it.next();
  51. String value = props.getProperty(id);
  52. if(id.equals("log4j.appender.DATABASE.driver")){
  53. driver = value;
  54. }else if(id.equals("log4j.appender.DATABASE.URL")){
  55. url = value;
  56. }else if(id.equals("log4j.appender.DATABASE.username")){
  57. username = value;
  58. }else if(id.equals("log4j.appender.DATABASE.password")){
  59. password = value;
  60. }
  61. // System.out.println(id + ":=" + value);
  62. }
  63. } catch (Exception e) {
  64. // TODO Auto-generated catch block
  65. e.printStackTrace();
  66. } finally {
  67. try {
  68. istream.close();
  69. } catch (IOException e) {
  70. // TODO Auto-generated catch block
  71. e.printStackTrace();
  72. }
  73. }
  74. }
  75. }
package dao; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Iterator; import java.util.Properties; import java.util.Set; public final class JdbcUtils { // private static String url = null; private static String driver = null; private static String username = null; private static String password = null; private JdbcUtils() { } static{ try { getProperties(); Class.forName(driver); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, username, password); } public static void close(Connection conn) { try { if (conn != null) conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void getProperties() { Properties props = new Properties(); FileInputStream istream = null; try { istream = new FileInputStream("log4j.properties"); props.load(istream); Set s = props.keySet(); Iterator it = s.iterator(); while (it.hasNext()) { String id = (String) it.next(); String value = props.getProperty(id); if(id.equals("log4j.appender.DATABASE.driver")){ driver = value; }else if(id.equals("log4j.appender.DATABASE.URL")){ url = value; }else if(id.equals("log4j.appender.DATABASE.username")){ username = value; }else if(id.equals("log4j.appender.DATABASE.password")){ password = value; } // System.out.println(id + ":=" + value); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { istream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }

Dao中的包——StudentsUtil.java/UserUtil.java: 对各自的表进行数据库的操作

Java代码 复制代码 收藏代码
  1. package dao;
  2. import java.sql.Connection;
  3. import java.sql.SQLException;
  4. import java.sql.Statement;
  5. public class StudentsUtil {
  6. public static int insertStudent(String sql) {
  7. Connection conn = null;
  8. Statement sm = null;
  9. int flag = 0;
  10. try {
  11. conn = JdbcUtils.getConnection();
  12. sm = conn.createStatement();
  13. sm.execute(sql);
  14. flag = 1;
  15. } catch (SQLException e) {
  16. // TODO Auto-generated catch block
  17. System.out.println("insert fail!");
  18. } finally {
  19. if (sm != null) {
  20. try {
  21. sm.close();
  22. } catch (SQLException e) {
  23. // TODO Auto-generated catch block
  24. e.printStackTrace();
  25. }
  26. }
  27. JdbcUtils.close(conn);
  28. }
  29. return flag;
  30. }
  31. public static String insertSql() {
  32. return "INSERT INTO StudentMessage(Name,Age,***,Time) values(";
  33. }
  34. }
  35. //===============================================
  36. package dao;
  37. import java.sql.CallableStatement;
  38. import java.sql.Connection;
  39. import java.sql.ResultSet;
  40. import java.sql.SQLException;
  41. import java.sql.Statement;
  42. import bean.UserBean;
  43. public class UserUtil {
  44. public static int insertUser(String sql) {
  45. Connection conn = null;
  46. Statement sm = null;
  47. int flag = 0;
  48. try {
  49. conn = JdbcUtils.getConnection();
  50. sm = conn.createStatement();
  51. sm.execute(sql);
  52. flag = 1;
  53. } catch (SQLException e) {
  54. // TODO Auto-generated catch block
  55. System.out.println("insert fail!");
  56. } finally {
  57. if (sm != null) {
  58. try {
  59. sm.close();
  60. } catch (SQLException e) {
  61. // TODO Auto-generated catch block
  62. e.printStackTrace();
  63. }
  64. }
  65. JdbcUtils.close(conn);
  66. }
  67. return flag;
  68. }
  69. public static String insertSql(){
  70. return "INSERT INTO LogMessage(Time,Note,Username,Password) values(";
  71. }
  72. }
package dao; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; public class StudentsUtil { public static int insertStudent(String sql) { Connection conn = null; Statement sm = null; int flag = 0; try { conn = JdbcUtils.getConnection(); sm = conn.createStatement(); sm.execute(sql); flag = 1; } catch (SQLException e) { // TODO Auto-generated catch block System.out.println("insert fail!"); } finally { if (sm != null) { try { sm.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } JdbcUtils.close(conn); } return flag; } public static String insertSql() { return "INSERT INTO StudentMessage(Name,Age,***,Time) values("; } } //=============================================== package dao; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import bean.UserBean; public class UserUtil { public static int insertUser(String sql) { Connection conn = null; Statement sm = null; int flag = 0; try { conn = JdbcUtils.getConnection(); sm = conn.createStatement(); sm.execute(sql); flag = 1; } catch (SQLException e) { // TODO Auto-generated catch block System.out.println("insert fail!"); } finally { if (sm != null) { try { sm.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } JdbcUtils.close(conn); } return flag; } public static String insertSql(){ return "INSERT INTO LogMessage(Time,Note,Username,Password) values("; } }

test包——test.java :测试类

Java代码 复制代码 收藏代码
  1. package test;
  2. import java.lang.reflect.InvocationTargetException;
  3. import org.apache.log4j.Logger;
  4. import org.apache.log4j.MDC;
  5. import org.apache.log4j.PropertyConfigurator;
  6. import org.apache.log4j.jdbc.JDBCAppender;
  7. import org.omg.CORBA.Request;
  8. import dao.GetObject;
  9. import bean.Students;
  10. import bean.UserBean;
  11. public class Test {
  12. public static void main(String[] args) {
  13. Test dbt = new Test();
  14. dbt.testUser();
  15. }
  16. public void testUser() {
  17. try {
  18. GetObject go = new GetObject();
  19. UserBean ub = go.insertInfo("TIBCO-VANCEINFO", "TIBCO-12345");
  20. go.getMethod(ub);
  21. // Students st = go.insertInfo("TIBCO", 21, 2);
  22. // go.getMethod(st);
  23. } catch (SecurityException e) {
  24. // TODO Auto-generated catch block
  25. e.printStackTrace();
  26. }
  27. }
  28. }
package test; import java.lang.reflect.InvocationTargetException; import org.apache.log4j.Logger; import org.apache.log4j.MDC; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.jdbc.JDBCAppender; import org.omg.CORBA.Request; import dao.GetObject; import bean.Students; import bean.UserBean; public class Test { public static void main(String[] args) { Test dbt = new Test(); dbt.testUser(); } public void testUser() { try { GetObject go = new GetObject(); UserBean ub = go.insertInfo("TIBCO-VANCEINFO", "TIBCO-12345"); go.getMethod(ub); // Students st = go.insertInfo("TIBCO", 21, 2); // go.getMethod(st); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

结果见附加:stuM.png/logM.png

阅读(1497) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~