Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a .sql script using MySQL with JDBC

Tags:

java

sql

mysql

jdbc

I am starting to use MySQL with JDBC.

Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql:///x", "x", "x"); stmt = conn.createStatement(); stmt.execute( "CREATE TABLE amigos" +             "("+             "id          int AUTO_INCREMENT          not null,"+             "nombre      char(20)                    not null,"+             "primary key(id)" +             ")"); 

I have 3-4 tables to create and this doesn't look good.

Is there a way to run a .sql script from MySQL JDBC?

like image 555
Macarse Avatar asked Jun 25 '09 14:06

Macarse


People also ask

Does JDBC work with MySQL?

To connect to MySQL from Java, you have to use the JDBC driver from MySQL. The MySQL JDBC driver is called MySQL Connector/J. You find the latest MySQL JDBC driver under the following URL: http://dev.mysql.com/downloads/connector/j. The download contains a JAR file which we require later.

How does JDBC connect to MySQL?

In Java, we can connect to our database(MySQL) with JDBC(Java Database Connectivity) through the Java code. JDBC is one of the standard APIs for database connectivity, using it we can easily run our query, statement, and also fetch data from the database.

Which method is used in JDBC to execute SQL query?

Once you have a Statement instance, you can execute a SELECT query by calling the executeQuery(String) method with the SQL you want to use. To update data in the database, use the executeUpdate(String SQL) method.


1 Answers

Ok. You can use this class here (posted on pastebin because of file length) in your project. But remember to keep the apache license info.

JDBC ScriptRunner

It's ripoff of the iBatis ScriptRunner with dependencies removed.

You can use it like this

Connection con = .... ScriptRunner runner = new ScriptRunner(con, [booleanAutoCommit], [booleanStopOnerror]); runner.runScript(new BufferedReader(new FileReader("test.sql"))); 

That's it!

like image 110
jitter Avatar answered Sep 18 '22 06:09

jitter