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?
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With