【问题标题】:mysql insert too slowmysql插入太慢
【发布时间】:2025-12-20 17:35:17
【问题描述】:

mysql server config 这里是mysql config,一个很简单的表,innodb,索引不多,但是有时候insert 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
**/

【问题讨论】:

标签: java mysql innodb


【解决方案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

【讨论】:

  • 谢谢n0xew,但我确定get Connection 没有任何业务。因为我记录了执行时间,从线程开始到env.logTiming("beforeGetConnection");程序花费了14ms,而当它运行到Connection conn = MySql.getInst_education_biz().getConnection();是20ms,这意味着获得一个连接只花费了6ms,你可以在下面看到其他花费代码。 pstmt.executeUpdate(); 上的大部分时间成本我在 mysql 服务器 cli 上尝试了这个 sql,结果相同。
  • 我的 mysql 服务器硬件配置也在我的 java 代码下面的 cmets 中。
  • 我很确定数据库在连接关闭后会释放一些资源,因此需要更多时间来处理可能的传入连接和查询。这当然取决于您的查询频率。无论如何,更新我的答案以使用ConnectionPool,这只能在出现其他问题时帮助您。
  • 我已经有一个ConnectionPool,我说最后一个raw返回ConnectionPool的连接
  • 抱歉,没有看到您的回复。另外,我在您的屏幕截图上看不到,每个查询间隔多少时间?