使用元数据在mysql中插入查询

时间:2014-11-25 09:54:18

标签: java mysql jdbc sql-insert

我有一个列表,其中包含表的列名

String tableName="employee";
ResultSet rs = Statement.executeQuery("SELECT * FROM"+tableName);
    ResultSetMetaData   rmd = rs.getMetaData();
        int columnCount = rmd.getColumnCount();
        List columnsList = new ArrayList();
        for (int i = 1; i <= columnCount; i++) {
            columnsList.add(rmd.getColumnName(i));
        }

列出值= [某些值];

now columnsList =[emp_id, name, salary, department];

现在我想使用这些列名来编写插入查询。但是我不想硬编码列名,我想从列表中获取这些名称并将它们传递给列名,如

   String subQuery= "insert into"+tableName+......here i want to get column names from list.....+.......here values from another list......;

有没有办法得到这个

3 个答案:

答案 0 :(得分:1)

一直在谷歌搜索我的#@ $寻找代码发货地来动态生成元数据的JDBC插入语句。请参阅generateInsertStatements()

private static void generateInsertStatements(Connection conn, String tableName)
throws Exception {
    log("Generating Insert statements for: " + tableName);
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); 
    ResultSetMetaData rsmd = rs.getMetaData();
    int numColumns = rsmd.getColumnCount();
    int[] columnTypes = new int[numColumns];
    String columnNames = "";
    for (int i = 0; i < numColumns; i++) {
        columnTypes[i] = rsmd.getColumnType(i + 1);
        if (i != 0) {
            columnNames += ",";
        }
        columnNames += rsmd.getColumnName(i + 1);
    }

    java.util.Date d = null; 
    PrintWriter p = new PrintWriter(new FileWriter(tableName + "_insert.sql"));
    p.println("set sqlt off");
    p.println("set sqlblanklines on");
    p.println("set define off");
    while (rs.next()) {
        String columnValues = "";
        for (int i = 0; i < numColumns; i++) {
            if (i != 0) {
                columnValues += ",";
            }

            switch (columnTypes[i]) {
                case Types.BIGINT:
                case Types.BIT:
                case Types.BOOLEAN:
                case Types.DECIMAL:
                case Types.DOUBLE:
                case Types.FLOAT:
                case Types.INTEGER:
                case Types.SMALLINT:
                case Types.TINYINT:
                    String v = rs.getString(i + 1);
                    columnValues += v;
                    break;

                case Types.DATE:
                    d = rs.getDate(i + 1); 
                case Types.TIME:
                    if (d == null) d = rs.getTime(i + 1);
                case Types.TIMESTAMP:
                    if (d == null) d = rs.getTimestamp(i + 1);

                    if (d == null) {
                        columnValues += "null";
                    }
                    else {
                        columnValues += "TO_DATE('"
                                  + dateFormat.format(d)
                                  + "', 'YYYY/MM/DD HH24:MI:SS')";
                    }
                    break;

                default:
                    v = rs.getString(i + 1);
                    if (v != null) {
                        columnValues += "'" + v.replaceAll("'", "''") + "'";
                    }
                    else {
                        columnValues += "null";
                    }
                    break;
            }
        }
        p.println(String.format("INSERT INTO %s (%s) values (%s)\n/", 
                                tableName,
                                columnNames,
                                columnValues));
    }
    p.close();
}

其他Metadata Example

答案 1 :(得分:0)

如果您以相同的顺序传递与表中列数相同的输入值,则无需提供列名。例如,您可以简单地编写为

插入值(val1,val2,.....)

如果您没有指定列名,那么mysql将自动考虑所有列。 但是这种写作方法是一种非常糟糕的方法,难以维护并且可能引入意想不到的错误。

答案 2 :(得分:0)

如果您已在List中拥有列名,则可以使用Apache Commons Lang中的StringUtils.join来构建以逗号分隔的列表,并将其包含在SQL语句中:

// the following code assumes: import org.apache.commons.lang.*;
String tableName="employee";
List<String> columnsList = new ArrayList<String>();
columnsList.add("emp_id");  //
columnsList.add("name");    // sample data
columnsList.add("salary");  //
String colString = StringUtils.join(columnsList, ',');
String paramString = StringUtils.repeat(",?", columnsList.size());
String sql = String.format(
        "INSERT INTO %s (%s) VALUES (%s)", 
        tableName, colString, paramString.substring(1));
System.out.println(sql);

导致

INSERT INTO employee (emp_id,name,salary) VALUES (?,?,?)

编辑:请注意,为了安全起见,您可能应该增强上面的代码,将表格和列名称括在反引号中,例如:

INSERT INTO `employee` (`emp_id`, ...