I have a Java SQL question relative to the insert method. If I have a database with multiple tables, I want to write a single insert method that can insert a row of data into any selected table for any type of relational database. If some tables contain different data types, for examples (integer, date, varchar, and etc.). My codes:
public void insertData(String tablename, String... values)
throws SQLException {
Connection con = null;
PreparedStatement prepStmt = null;
if (values.length == 0) {
throw new SQLException("Must supply values");
}
try{
con = getConnection();
String sql = "insert into "+tablename+" values(";
for (int i = 0; i < values.length; i++) {
sql += "?";
if (i != values.length-1) sql += ",";
}
sql += ")";
prepStmt = con.prepareStatement(sql);
for (int i = 0; i < values.length; i++) {
prepStmt.setString(i, values[i]);
}
prepStmt.executeUpdate();
}
finally {
closeStatement(prepStmt);
closeConnection(con);
}
}
For example, use case:
Table Teacher has int id, varchar(50) name, int age, text subject, int classid;
Table Student has int id, varchar(50) name, date dateofbirth, text address;
Table Class has int id, text subject;
If I use:
insertData(Teacher, new String[] {"10", "Cass", "32", "Math", "10222"});
Will that data insert into the table successfully? I heard the database is only using varchar. If that is the case, then I don't have to worry about the type. If the type is varchar, should I use prepStmt.setString()?
I need to support multiple different types of database, such like SQL Server, MySQL, Oracle and others. Will that one insertData() method work for all different databases?
The database meta data can tell you the details of the table.
What you can do is using DatabaseMetaData
to get the column names, types and size, then you can choose PreparedStatement
corresponding setXXX methods:
DatabaseMetaData metadata = connection.getMetaData();
ResultSet resultSet = metadata.getColumns(null, null, "mytable", null); // table name is mytable
while (resultSet.next()) {
String name = resultSet.getString("COLUMN_NAME");
String type = resultSet.getString("TYPE_NAME");
int size = resultSet.getInt("COLUMN_SIZE");
}
Another way is using ResultSetMetaData
but you have to query from the table to get the ResultSet
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount() ; // returns the number of columns
for(int i = 1; i < columnCount + 1; i++){
rsmd.getColumnName(i); //get name
}
After you get the table's information(column name, type...), then you can choose proper query to update the table
您的方案仅在您为每列传递值时才会起作用,如果表中有任何可为空的列,并且您不想在其上插入值,那么它将无效并且将抛出sql异常,因为您必须指定在insert语句中也是列名,但在你的情况下,你可以传递Object数组而不是String数组,然后根据你可以从getClass方法中获得的参数的类类型调用适当的setXXX。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.