Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

get - Access string variable outside for loop in java?

hi folks i want to access a string variable outside for loop, so that i can use it for further coding. Here i am trying to get the values from Jtable and store it in string, to create a database table. The Whole Code is here: 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){}

   }


    }

Thank You.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to understand what local variables are and what is their lifetime. I suggest reading through this tutorial: http://www.tutorialspoint.com/java/java_variable_types.htm

In you case, just declaring readstr outside the for loop would do what you want.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...