Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Prepare a statement without a connection

Tags:

java

sql

I'm trying to generate some sql files in my java application. The application will not execute any sql statements, just generate a file with sql statements and save it.

I'd like to use the java.sql.PreparedStatement to create my statements so that i don't have to validate every string etc. with my own methods.

Is there a way to use the PreparedStatement without the calling java.sql.Connection.prepareStatement(String) function, because I don't have a java.sql.Connection?

like image 901
oliver31 Avatar asked May 20 '10 12:05

oliver31


3 Answers

Take a look at this Java library: http://openhms.sourceforge.net/sqlbuilder/

like image 82
PeterMmm Avatar answered Sep 18 '22 12:09

PeterMmm


I'm guessing that until you've got a sql connection, the parser won't know what rules to apply. I'm guessing that it's actually the SQL driver or even server that's compiling the sql statement.

Assuming your sql is simple enough, then how about using a cheap connection, like, say a sqlite connection.

SQLite will create a new database on the fly if the database you're attempting to connect to does not exist.

public Connection connectToDatabase() {

// connect to the database (creates new if not found)
try {
    Class.forName("org.sqlite.JDBC");
    conn = DriverManager.getConnection("jdbc:sqlite:mydatabase.db");

    // initialise the tables if necessary
    this.createDatabase(conn);
}
catch (java.lang.ClassNotFoundException e) {
    System.out.println(e.getMessage());
}
catch (java.sql.SQLException e) {
    System.out.println(e.getMessage());
}

return conn;

}
like image 26
blissapp Avatar answered Sep 17 '22 12:09

blissapp


Not really. Preparing a statement in most cases means that it will be compiled by DBMS which is "hard" without connection.

http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html

like image 29
Anton Avatar answered Sep 20 '22 12:09

Anton