【发布时间】:2014-12-17 22:08:08
【问题描述】:
我正在尝试将值插入 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。
什么可能导致这个问题(没有插入行并且没有报告错误)?
【问题讨论】:
-
使用
PreparedStatement而不是普通的Statement。