我是新手,并尝试使用预处理语句将一些日期添加到Oracle数据库中。这是我的代码:
CODE REMOVED, code updated.
这会产生以下结果:
INSERT into TEST_RESULTS12233 (DB_ID, DATED1, DATED2, DATED3, DATED4) values (t1_seq.nextval, to_date(?, 'dd/mm/yyyy hh24.mi'), to_date(?, 'dd/mm/yyyy hh24.mi'), to_date(?, 'dd/mm/yyyy hh24.mi'), to_date(?, 'dd/mm/yyyy hh24.mi'))
Event1
Event2
Event3
Event4
Exception in thread "main" java.sql.BatchUpdateException: ORA-01858: a non-numeric character was found where a numeric was expected
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10500)
at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:230)
at sandpit.testsand.main(testsand.java:85)
如果我将setString中的pstatement替换为Event1,则批处理执行。 有谁知道我怎么能让这个工作? 感谢
以下是所要求的完整代码:
//MORE CODE AS REQUESTED
String inserttotable = "INSERT into TEST_RESULTS12233 (DB_ID";
String stateclose = ")";
String insertvalues =(" values (t1_seq.nextval");
StringBuilder insertBuilder = new StringBuilder();
StringBuilder valueBuilder = new StringBuilder();
int timestoloop = 4;
for (i=1; i<=timestoloop; i++)
{
insertBuilder.append(", DATED"+i);
valueBuilder.append(", to_date(?, 'dd/mm/yyyy hh24.mi')");
}
String finalinsert = inserttotable + insertBuilder.toString()+ stateclose;
String finalvalues = insertvalues + valueBuilder.toString() + stateclose;
String insertsql = finalinsert + finalvalues;
System.out.println(insertsql);
String insertresults = insertsql;
PreparedStatement prepState = conn.prepareStatement(insertresults);
String Event1 = "22122014 13.26";
String Event2 = "22122014 13.27";
String Event3 = "22122014 13.28";
String Event4 = "22122014 13.29";
for (i=1; i<=timestoloop; i++)
{
String pstatement = "Event"+i;
System.out.println(pstatement);
prepState.setString(i, pstatement);
}
prepState.addBatch();
prepState.executeBatch();
答案 0 :(得分:3)
通过将计数器附加为String
文字(Event1
)并将其作为String
输入设置为预准备语句,您可以动态创建变量名称。您实际上是设置String
文字,如(Event1
)而不是值(22122014 13.26
)。这不是您应该做的方式。您可能必须直接设置值,如
prepState.setString(1, Event1);
prepState.setString(2, Event2);
prepState.setString(3, Event3);
prepState.setString(4, Event4);
我建议你去找一个包含所有Event值的String文字列表。迭代它们并在Prepared语句中设置它们并执行查询。
List<String> eventValues = new ArrayList<String>();
答案 1 :(得分:0)
我相信你提到你已经尝试了一个arraylist但它应该看起来像这样:
List<String> events=new ArrayList<String>();
events.add("22122014 13.26");
events.add("22122014 13.27");
events.add("22122014 13.28");
events.add("22122014 13.29");
for (i=1; i<=timestoloop; i++)
{
String pstatement = "Event"+i;
System.out.println(pstatement);
prepState.setString(i, events.get(i));
prepState.addBatch();
}
你正在使用字符串&#34; Event1&#34;来自您的变量而不是实际变量。 prepState.setString(i,&#34; event&#34; + i)不等于prepState.setString(i,event1)。一个只返回一个字符串,一个只是一个包含字符串值的变量,后者是你想要的那个。