问题
I want to insert a set of arrays into a database(HANA) in a loop.My code is below:
public class jdemo {
public static void main(String[] args) {
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:sap://myhdb:30715/?autocommit=false",myname,mysecret);
} catch (SQLException e) {
System.err.println("Connection Failed. User/Passwd Error?");
return;
}
if (connection != null) {
try {
int [] array=new int []{1,2,3};
Array array1= connection.createArrayof("Integer",array)
System.out.println("Connection to HANA successful!");
String sql="INSERT INTO TABLE1 VALUES(1,ARRAY(?))"
PreparedStatement stmt = connection.createStatement(sql);
stmt.setArray(int,array1);
stmt.executeUpdate(sql);
} catch (SQLException e) {
System.err.println("Query failed!");
}
}
}
}
But this does not work. I tried with
Object [] array=new Object []{1,2,3};
This returned method create array of Connection is not supported.
My Table Schema looks like
ID MARK
__ ____
10 {1,2,3}
11 {3,2,3}
12 {9,2,3}
13 {10,2,3}
14 {12,24,3}
18 {1,27,3}
I also want my data type as an integer array.Any help is appreciated.
回答1:
The topic of "ARRAY inserts into HANA" has been discussed a couple of times here on SO already. HANA only supports to store arrays via the ARRAY() function. This function does not take a list as the parameter, but only separate elements.
So, instead of
String sql="INSERT INTO TABLE1 VALUES(1,ARRAY(?))"
you would have to write
String sql="INSERT INTO TABLE1 VALUES(1, ARRAY( 1, 2, 3))"
For the JDBC driver: HANA JDBC doesn't automatically handle JAVA arrays to HANA arrays - that's something the developer will have to do manually. (yes, it's not nice, I know).
In short: currently (HANA 1.0 SP12) arrays can basically be used internally (within a stored procedure), but they are not first-class-citizen data types. (<- that's my opinion!)
回答2:
Just an idea:
Instead of storing an array in your column, you can save a string separated by colons. When you query the data from your database, you can use split(","), and you automatically have your array that you need (after Integer.parseInt(String))
回答3:
You are using createStatement instead of prepareStatement. createStatement does nut support parameters!
Check https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html
And https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
for details Hope this helps
Would be nice if you provide DDL, error messages etc. next time, then its easier to analyze.
来源:https://stackoverflow.com/questions/41625922/how-to-insert-an-array-in-a-loop-to-the-database