Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JDBC: How to create the tables?

I am using Spring JdbcTemplate with the DAO pattern to access a database. Instead of creating the database tables manually, I am looking for a way to generate the tables in the DAO layer. I understand that I can use the JdbcTemplate to execute statements, I am only looking for the right place to do it.

Is there a best practice for that?

like image 838
Juri Glass Avatar asked Jan 20 '10 12:01

Juri Glass


People also ask

Can we create a table using JDBC?

There are four steps for creating a table using JDBC API. Open connection to the database. Create a statement object to perform a create table query. Execute the executeUpdate() method of statement object to submit a query to database.

What is difference between JDBC and Spring JDBC?

The Spring JDBC Template has the following advantages compared with standard JDBC. The Spring JDBC template allows to clean-up the resources automatically, e.g. release the database connections. The Spring JDBC template converts the standard JDBC SQLExceptions into RuntimeExceptions.

What is Spring JDBC template?

Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC api, but eliminates a lot of problems of JDBC API.

How does JDBC template connect to database?

First, install some DDL by using the execute method of JdbcTemplate . Second, take a list of strings and, by using Java 8 streams, split them into firstname/lastname pairs in a Java array. Then install some records in your newly created table by using the batchUpdate method of JdbcTemplate .


1 Answers

You can use the execute(String) method:

public void execute(String sql) throws DataAccessException

Issue a single SQL execute, typically a DDL statement.
Specified by: execute in interface JdbcOperations

Parameters: sql - static SQL to execute

Throws: DataAccessException - if there is any problem

However as beny23 mentions I would be suspicious of an actual need to do this programatically in a live application.

like image 89
matt b Avatar answered Oct 10 '22 06:10

matt b