mysql插入太慢了

时间:2017-07-02 10:14:08

标签: java mysql innodb

mysql server config     这里是mysql配置,一个非常简单的表,innodb并没有多少索引,但有时插入op太慢了,有人可以告诉我为什么吗?

public Long insertCoursewarePage(Env env, Long coursewareId, Integer pageType, String teacherId) throws SQLException {
    env.logTiming("beforeGetConnection");
    Connection conn = MySql.getInst_education_biz().getConnection();
    env.logTiming("afterGetConnection");
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    String sql = "INSERT INTO `courseware_page`(`courseware_id`, `page_type`, `teacher_id`, `create_time`) VALUES(?,?,?,?)";
    try {
        pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        env.logTiming("afterPrepareStatement");
        pstmt.setLong(1, coursewareId);
        pstmt.setInt(2, pageType);
        pstmt.setString(3, teacherId);
        pstmt.setLong(4, System.currentTimeMillis());
        pstmt.executeUpdate();
        env.logTiming("afterExecuteUpdate");
        rs = pstmt.getGeneratedKeys();
        env.logTiming("afterGetGeneratedKeys");
        if (rs.next()) {
            return rs.getLong(1);
        }
    } finally {
        MySql.closeConnection(rs, pstmt, conn);
    }
    return null;
}
/**
Here is my java code, use jdbc get a connection and I profiled it and the result is below here. 
beforeGetConnection=14
afterGetConnection=20
afterPrepareStatement=20
afterExecuteUpdate=5344
afterGetGeneratedKeys=5345
mysql server is on a dell r820, SSD, 64 core cpu, 320G memory, it seems no any problem.so could anybody tell me why
**/

1 个答案:

答案 0 :(得分:1)

这可能是因为每次您要插入时都会打开与Connection conn = MySql.getInst_education_biz().getConnection();的连接,然后您执行查询并在之后关闭MySql.closeConnection(rs, pstmt, conn);

您的插入时间可能很短,但为每个查询打开和关闭连接的成本很高。如果经常查询您的数据库,您可能希望使用只会暂停"连接和"恢复"它在需要的时候。以下是使用它的一些原因:https://plumbr.eu/blog/io/acquiring-jdbc-connections-what-can-possibly-go-wrong