As we know, we can use jdbc to access database in java programming. And now let us use jdbc in spring. The spring framework reduces developer handlers any accessing database exception, because it deal with them internally. The spring framework integrated the jdbctemplate, they are org.springframework.jdbc.datasource.DriverManagerDataSource and org.springframework.jdbc.core.JdbcTemplate.
And here we use the hsqldb to act as our memory database. You can go to here to look at it. we use the Maven tools to management our project. the dependencies is:
we have a SpringJdbcCreateTable class to accesss database, this class has `JdbcTemplate` property, ``` java JdbcTemplate jt;
public void setJt(JdbcTemplate jt) { this.jt = jt; }
we use spring bean to inject value to this property. And you will see it in above spring configure file.
create table, the execute method doesn’t return value.
1 2 3 4 5
publicvoidcreateTable() { jt.execute("CREATE TABLE user(id int, name varchar(10), age int)"); // execute() returns void System.out.println("table created"); }
insert data, using the update method to insert data, this method will return how many rows have been inserted.
1 2 3 4 5 6
publicvoidinsertData() { intk= jt.update("INSERT INTO user VALUES (99, 'user_99', 49)"); showDatas(); System.out.println(String.format("%s row inserted", k)); }
update data, using the update method to update data, it will return how many rows are affected.
1 2 3 4 5 6
publicvoidupdateData() { intk= jt.update("UPDATE user set name='user_new' where name='user_99'"); showDatas(); System.out.println(String.format("%s row updated", k)); }
delete data, also using the update method.
1 2 3 4 5 6
publicvoiddeleteData() { intk= jt.update("DELETE from user where name='user_new'"); showDatas(); System.out.println(String.format("%s row deleted", k)); }
query data, the jdbctemplate has many query interfaces. Here we use queryForRowSet method to get the data by condition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
privatevoidshowDatas() { System.out.println("| ID | NAME | AGE |"); SqlRowSetrowSet= jt.queryForRowSet("SELECT * FROM user");
while (rowSet.next()) { intid= rowSet.getInt(1); Stringname= rowSet.getString(2); intage= rowSet.getInt(3);