鍍金池/ 問答/Java  數(shù)據(jù)庫/ java如何執(zhí)行sql腳本并傳參

java如何執(zhí)行sql腳本并傳參

如下所示,利用ant.jar實現(xiàn)連接oracle數(shù)據(jù)庫并執(zhí)行sql腳本,但是如果我的sql腳本是帶傳入?yún)?shù)的(例如通過sqlplus是這樣執(zhí)行:sqlplus user/password@db @test.sql A B C),貌似ant.jar中并不支持腳本傳參,不知道有什么好的方法?

public static void main(String[] args) {
SQLExec sqlExec = new SQLExec();
//設(shè)置數(shù)據(jù)庫參數(shù)
sqlExec.setDriver("oracle.jdbc.driver.OracleDriver");
sqlExec.setUrl("jdbc:oracle:thin:@10.128.x.x:1521:xxsid");
sqlExec.setUserid("xxuser");
sqlExec.setPassword("xxpass");
//要執(zhí)行的腳本
sqlExec.setSrc(new File("src/data.sql"));
//有出錯的語句該如何處理
sqlExec.setOnerror((SQLExec.OnError)(EnumeratedAttribute.getInstance(
SQLExec.OnError.class, "abort")));
sqlExec.setPrint(true); //設(shè)置是否輸出
//輸出到文件 sql.out 中;不設(shè)置該屬性,默認輸出到控制臺
sqlExec.setOutput(new File("src/sql.out"));
sqlExec.setProject(new Project()); // 要指定這個屬性,不然會出錯
sqlExec.execute();
}

回答
編輯回答
好難瘦

有很多好東西可以做數(shù)據(jù)庫相關(guān)的操作。

  1. JDBC:寫SQL進行查詢
  2. MyBatis:對象映射
  3. Hibernate:對象映射

另外,main方法的args是可以傳參數(shù)的。你可以把參數(shù)傳入,然后用最笨的辦法把參數(shù)和SQL用String.format組合起來。
比如通過args傳入的參數(shù)是ABC,代碼可以是如下這樣寫:

String.format("select * from table where name=%s and age=%s and sex=%s", A, B, C)
2017年8月14日 17:23