2010-05-20 5 views
7

Java 응용 프로그램에서 일부 sql 파일을 생성하려고합니다. 아니요은 SQL 문을 실행하고 파일을 생성 한 다음 저장하면됩니다.Java : 연결하지 않고 명령문 준비

내 문장을 만들 때 java.sql.PreparedStatement을 사용하여 모든 문자열 등을 내 자신의 방법으로 검증 할 필요가 없습니다.

java.sql.Connection이 없기 때문에 java.sql.Connection.prepareStatement(String) 함수를 호출하지 않고 PreparedStatement 함수를 사용할 수 있습니까?

답변

3

이 자바 라이브러리를 살펴 보자 감사 http://openhms.sourceforge.net/sqlbuilder/

+0

이 라이브러리는 포함되지 않은 "com.healthmarketscience.common.util"패키지를 가져옵니다. – r3zn1k

+0

조금만 돌아 가야합니다. http://openhms.sourceforge.net/common-util/ – PeterMmm

+0

최고의 솔루션. 많은 감사합니다! – r3zn1k

3

당신은 SQL 연결을 가지고 때까지 파서 규칙이 적용 해야할지 것 같은데요. 나는 그것이 실제로 SQL 드라이버 또는 심지어 SQL 문을 컴파일하는 서버라고 추측하고 있습니다.

여러분의 sql이 간단하다고 가정하면 sqlite 연결과 같은 값싼 연결을 사용하는 것이 좋습니다.

연결하려는 데이터베이스가 존재하지 않으면 SQLite는 새로운 데이터베이스를 즉석에서 생성합니다.

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; 

} 
+0

그럼 연결할 대상이 없는데 어떻게 연결을 만들 수 있습니까? – r3zn1k

+0

sqlite가 존재하지 않으면 새로운 데이터베이스를 생성합니다 - 개념 코드 예제 코드 – blissapp

+0

업데이트를 추가하면 SQLite 데이터베이스가 연결 문자열 "jdbc : sqlite :: memory :"로만 메모리에 생성 될 수 있음을 배웠습니다 – blissapp

0

PreparedStatement를 구현해보십시오.

예 : 클래스 YourOwnClass는 모든 메소드를 구현 함 {

// 1의 PreparedStatement를 구현 2 OraclePreparedStatement (에 classes12.jar) 또는 sun.jdbc.odbc.JdbcOdbcCallableStatement에서 구현하기 위해 최소한의 논리를 가져옵니다

}

+0

정규식이나 그와 비슷한 것을 사용하는 것이 훨씬 쉽습니다 ... – r3zn1k

+0

@ r3zn1k :이 구현의 장점은 코드를 다시 사용할 수 있다는 것입니다. 텍스트 SQL을 생성하거나 직접 SQL을 실행할 수 있습니다. 그러나 당신이 그 융통성을 필요로하지 않는다면 나는 놀라지 않을 것입니다. :) –

0

이것은 비열한 우회하는 문제입니다 완전히는 대처하기 매우 쉽습니다 :

final String sql = "SELECT * FROM FOO WHERE USER = ?"; 
    PreparedStatementBuilder psBuilder = new PreparedStatementBuilder(sql){ 
     @Override 
     protected void preparePrepared(PreparedStatement preparedStatement) 
      throws SQLException 
     { 
      preparedStatement.setString(1, "randal"); 
     }}; 
    return obtainResultSet(psBuilder); 

프레스토 :

public class PreparedStatementBuilder 
{ 
    private String sql; // the sql to be executed 

    public PreparedStatementBuilder(final String sql) { this.sql = sql; } 

    protected void preparePrepared(final PreparedStatement preparedStatement) 
      throws SQLException 
    { 
     // this virtual method lets us declare how, when we do generate our 
     // PreparedStatement, we want it to be setup. 

     // note that at the time this method is overridden, the 
     // PreparedStatement has not yet been created. 
    } 

    public PreparedStatement build(final Connection conn) 
      throws SQLException 
    { 
     // fetch the PreparedStatement 
     final PreparedStatement returnable = conn.prepareStatement(sql); 
     // perform our setup directives 
     preparePrepared(returnable); 
     return returnable; 
    } 
} 

은 무효 preparePrepared을 무시 익명 클래스 (PreparedStatement로)를 작성, 사용하기! 이제는 PreparedStatement를 작성하지 않고 작업 할 수있는 방법이 있습니다. 다음은 다른 나라에 붙여 올 복사해야 할 것이다 최소한의 상용구를 보여주는 예입니다, 당신이 원하는 때마다 다른 문 쓰고 : 그 사방

public ResultSet obtainResultSet(final PreparedStatementBuilder builder) 
     throws SQLException { 
    final Connection conn = this.connectionSource.getConnection(); 
    try 
    { 
     // your "virtual" preparePrepared is called here, doing the work 
     // you've laid out for your PreparedStatement now that it's time 
     // to actually build it. 
     return builder.build(conn).executeQuery(); 
    } 
    finally 
    { 
     try { conn.close(); } 
     catch (SQLException e) { log.error("f7u12!", e); } 
    } 
} 

당신은 정말 정말되고 싶지 않아 복사 붙여 넣기, 너?

관련 문제