我正在尝试将值插入MySQL数据库。我没有错误(statement.executeUpdate(...)
返回1),但没有插入行。
我正在使用以下MySQL驱动程序:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
我像这样初始化连接:
public class MySqlPersistence implements IPersistence {
private static final Logger LOGGER = LoggerFactory.getLogger(MySqlPersistence.class);
private Connection connection;
private Statement statement;
@Override
public void init(final String aUserName, final String aPassword, final String aHost,
final String aDatabase, final int aPort) {
final String dbUrl = "jdbc:mysql://" + aHost + ":" + aPort + "/" + aDatabase;
final String schema = readSchemaCreationScript();
try
{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dbUrl, aUserName, aPassword);
connection.setAutoCommit(true);
statement = connection.createStatement();
new ScriptRunner(connection).runScript(new StringReader(schema));
} catch (final ClassNotFoundException e) {
LOGGER.error("", e);
} catch (final SQLException e) {
LOGGER.error("", e);
}
}
}
行插入如下:
@Override
public Long createRepositoryIfNotExists(final String aRepoPath) throws SQLException {
final String cleanPath = aRepoPath.replace('\\', '/');
final String sql2 = "INSERT INTO repositories (path) VALUES('" + cleanPath + "')";
int result = statement.executeUpdate(sql2);
ResultSet resultSet = statement.executeQuery("SELECT id FROM repositories WHERE path='" +
cleanPath + "'");
Long repoId = null;
if (resultSet.next())
{
repoId = resultSet.getLong("id");
}
resultSet.close();
return repoId;
}
当我在phpMyAdmin中执行sql2
时,插入了行,我没有收到任何错误。
MySQL服务器版本是5.5.40。
可能导致此问题的原因(未插入任何行且未报告错误)?
答案 0 :(得分:0)
可能会抛出异常或错误,并且在不留痕迹的情况下捕获它。您应该在插入之前和之后创建跟踪,以查看带有插入的行是否真正执行而没有错误。
答案 1 :(得分:0)
我通过在关闭连接之前调用commit来解决问题。
@Override
public void shutdown()
{
if (statement != null)
{
try {
statement.close();
} catch (SQLException e) {
LOGGER.error("", e);
}
}
if (connection != null)
{
try {
connection.commit(); // This statement fixed the problem
connection.close();
} catch (final SQLException e) {
LOGGER.error("", e);
}
}
}
我仍然不明白,为什么在打开连接时启用自动提交会有所帮助。