我试图探索Spring的jdbctemplate的基础知识。我在一个简单的例子中遇到了麻烦:
public static void main(String[] args) throws Exception {
JdbcDataSource dataSource = new JdbcDataSource();
String url = "jdbc:h2:mem:test";
dataSource.setURL(url);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute("create table something (id int primary key, name varchar(100))");
jdbcTemplate.execute("insert into something (id, name) values (1, 'Brian')");
}
触发:
Caused by: org.h2.jdbc.JdbcSQLException: Table "SOMETHING" not found; SQL statement:
insert into something (id, name) values (1, 'Brian') [42102-177]
如果我将该代码转换为使用原始JDBC api,它可以正常工作:
public static void main(String[] args) throws Exception {
JdbcDataSource dataSource = new JdbcDataSource();
String url = "jdbc:h2:mem:test";
dataSource.setURL(url);
try (Connection dbConnection = dataSource.getConnection()) {
try (Statement statement = dbConnection.createStatement()) {
statement.execute("create table something (id int primary key, name varchar(100))");
statement.execute("insert into something (id, name) values (1, 'Brian')");
try (ResultSet rs = statement.executeQuery("select id, name from something")) {
while (rs.next()) {
System.out.println(String.format("got result. id=%d. name=%s", rs.getInt(1), rs.getString(2)));
}
}
}
}
}
如果重要,我的Gradle依赖项:
compile 'org.springframework:spring-jdbc:4.0.6.RELEASE'
compile 'com.h2database:h2:1.4.177'
答案 0 :(得分:0)
请尝试使用update
方法execute
。