在java中循环访问字符串变量?

时间:2013-04-18 08:52:16

标签: for-loop get jtable

大家好我想在for循环外访问一个字符串变量,这样我就可以用它来进一步编码了。在这里,我试图从Jtable获取值并将其存储在字符串中,以创建数据库表。整个代码在这里:http://textuploader.com/?p=6&id=zVEWY

Coding :
int row = table.getRowCount();

int column = table.getColumnCount();

for (int j = 0; j < row; j++) {

for (int i = 0; i < column; i++) {

 //System.out.println(table.getValueAt(j, i));
  String readstr = (String) table.getValueAt(j, i);   // I WANT TO ACCESS THIS STRING


 }

 }


 try{
   // FILE READ AND TABLE CREATE
   String tname="example";
   String dbname="DB123";
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn= (Connection)    DriverManager.getConnection("jdbc:mysql://localhost:3306/DB123","root","");
    Statement stmt=(Statement) conn.createStatement();

    System.out.println("connect");



     DatabaseMetaData dmd = (DatabaseMetaData) conn.getMetaData();
     while((readstr=brr.readLine())!=null)                     // TO USE IT HERE
    {
     ResultSet rs = dmd.getTables(null,"MigrationDB", "example", null);
     //set not null column
     if (String.valueOf(readstr).contains("NO"))
  readstr=readstr.replaceAll("NO", "not null");
     else if(String.valueOf(readstr).contains("YES"))
       readstr=readstr.replaceAll("YES", "");
     if(String.valueOf(readstr).contains("PRIMARY"))
         readstr=readstr.replaceFirst("PRIMARY","primary key");
    System.out.println("replace string "+readstr);
  int k=1;
   if (!rs.next())
  {
  stmt.executeUpdate("CREATE TABLE "+tname+ "("+readstr+")");

    }
 else{
     System.out.println(readstr);
     stmt.executeUpdate("ALTER TABLE "+tname+ " ADD("+readstr+")");
      System.out.println("altered");

      }
     }

    }
     catch (Exception e){}

   }


    }

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要了解哪些局部变量以及它们的生命周期。我建议阅读本教程:http://www.tutorialspoint.com/java/java_variable_types.htm

在你的情况下,只需在for循环外声明readstr就能做到你想要的。

String readstr;
for(//loop condition) {
readstr = read value ;
}