需求,日志表命名格式为xxx+时间,判断前一天文件是否自动生成。
工具类:获取后缀时间详见日期时间工具类
代码:获取数据库连接,关闭连接,判断表是否存在
package utils;
import java.sql.*;
import java.util.Properties;
public class TableExistsUtils {
private static Connection connection = null;
/**
* 获取数据库连接
*
* @return
*/
public static Connection getConnection() {
PreparedStatement pre = null;
try {
/**
* 1.获取Driver实现类对象,使用反射
*/
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
/**
* 2.提供要连接的数据库
*/
String url = "jdbc:mysql://localhost:3306/ssm_mimi";
/**
* 3.提供连接需要的用户名和密码
*/
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "123456");
/**
* 4.获取连接
*/
connection = driver.connect(url, info);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
/**
* 关闭连接
*
* @param conn
*/
public static void close(Connection connection, PreparedStatement pst) {
if (pst != null) {
try {
pst.close();
pst = null;//如果没有关掉我们将它手动赋值为null
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 判断数据库中是否存在表
*
* @param code 表名
* @param conn 连接
* @return
*/
public static boolean isExists(String code, Connection conn) {
boolean result = false;
try {
DatabaseMetaData meta = conn.getMetaData();
ResultSet set = meta.getTables(null, null, code, null);
//判断数据库表是否存在
if (set.next()) {
result = true;
} else {
result = false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
功能实现
import models.bean.TableExists;
import net.sf.oval.constraint.Past;
import play.jobs.Every;
import play.jobs.Job;
import utils.DateUtils;
import utils.TableExistsUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TableExistsJob{
public void getTable(){
/**
* 获取数据库连接
*/
Connection connection = TableExistsUtils.getConnection();
TableExists tableExists = new TableExists();
/**
* 得到前一天的表名
*/
String yesterdayDateString = DateUtils.getYesterdayDateString();
String tableName = "pvlogs_" + yesterdayDateString;
/**
* 创建对象赋值
*/
tableExists.table_name = tableName;
/**
* 传入表名判断是否存在
*/
boolean exists = TableExistsUtils.isExists(tableName, connection);
if (exists) {
String sql = "select count(*) from " + tableName;
PreparedStatement past = null;
try {
past = connection.prepareStatement(sql);
ResultSet resultSet = past.executeQuery();
resultSet.next();
int count = resultSet.getInt(1);
tableExists.table_count = count;
} catch (SQLException e) {
e.printStackTrace();
} finally {
TableExistsUtils.close(connection, past);
}
} else {
tableExists.table_error = "数据表未及时更新!请尽快处理";
}
tableExists.save();
}
}