对于SQL Create Table查询中的循环

时间:2017-09-17 08:08:45

标签: java sql create-table vertica

我正在尝试使用JAVA在Vertica中创建表模型(i,y1,y2 .... yd)。列i是整数,其他所有都是REAL。我使用以下代码来创建它。但是它在null或接近null时显示语法错误。有谁知道这意味着什么?该连接适用于该程序。

 public void createMODEL(int d)
     {
         int x;
         try
     {

        Statement stmt = conn.createStatement();
        String createquery = "CREATE TABLE MODEL ( "
                            + "i integer primary key ";
        for (x=1;x<=d;x++) createquery+=  " , " + Y[x] + " REAL ";
        createquery += ")";
        stmt.executeUpdate(createquery);   
     }
     catch (Exception e)
     {
        System.out.println("Error while executing create model query");
        System.out.print(e);
        System.exit(0);

     }

 }

Y定义如下 -

String Y[]=new String[100];

2 个答案:

答案 0 :(得分:1)

我猜您应该检查Y[x]是否为空:

Statement stmt = conn.createStatement();
String createquery = "CREATE TABLE MODEL ( "
                            + "i integer primary key ";
for (x=1;x<=d;x++)  {
    if (Y[x] != null)  createquery+=  " , " + Y[x] + " REAL ";
}
createquery += ")";
stmt.executeUpdate(createquery);   

答案 1 :(得分:0)

这适用于MySQL。试试这个。

String Y[] = new String[100];
Y[0] = "h";
Y[1] = "ha";
Y[2] = "hat";
Y[3] = "hati";
Y[4] = "hatim";

System.out.println("Your columns array : " + Arrays.deepToString(Y));

String createquery = "CREATE TABLE MODEL ( " + "i integer primary key ";

for (int i = 0; i < Y.length; i++) {
    if (Y[i] != null)
        createquery += " , " + Y[i] + " REAL ";
}
createquery += ");";

System.out.println("Your create query : " + createquery);