时间:2021-07-01 10:21:17 帮助过:1人阅读
创建连接
package collect_part; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; public class MysqlConnection { public static Connection getConnection() { Connection conn = null; String url = "jdbc:mysql://10.1.1.148:3306/testresults"; String user = "user"; String password = "passwd"; try { conn = DriverManager.getConnection(url, user, password); } catch (SQLException ex) { Logger.getLogger(MysqlConnection.class.getName()).log(Level.SEVERE,null, ex); } return conn; } }
操作数据库
package collect_part; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; public class OperationDB { private Connection conn = null; public void addRcorder(InfoBean infoBean) throws SQLException { if (conn == null) { conn = MysqlConnection.getConnection(); } String sql = "INSERT INTO cpuInfo (`timeStamp`, `elapsed`, `grpThreads`, `allThreads`) VALUES (?, ?, ?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setLong(1, infoBean.getTimeStamp()); pstmt.setLong(2, infoBean.getElapsed()); pstmt.setLong(3, infoBean.getGrpThreads()); pstmt.setLong(4, infoBean.getAllThreads()); pstmt.executeUpdate(); } }
记录信息
package collect_part; public class InfoBean { long timeStamp; long elapsed; long grpThreads; long allThreads; public long getTimeStamp() { return timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = Long.parseLong(timeStamp); } public long getElapsed() { return elapsed; } public void setElapsed(String elapsed) { this.elapsed = Long.parseLong(elapsed); } public long getGrpThreads() { return grpThreads; } public void setGrpThreads(String grpThreads) { this.grpThreads = Long.parseLong(grpThreads); } public long getAllThreads() { return allThreads; } public void setAllThreads(String allThreads) { this.allThreads = Long.parseLong(allThreads); } }
java 每日习题(六)从文件收集数据记录到mysql
标签: