java string 循环,在java中循环之外访问字符串变量?

这段代码展示了如何从Java的JTable中读取数据,并使用这些数据来创建或修改MySQL数据库的表格。它遍历JTable的每一行和每一列,将值转换为字符串,然后处理这些字符串以适应数据库表结构(如替换特定关键字)。最后,通过JDBC连接到数据库,执行CREATE TABLE或ALTER TABLE语句。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

解决方案

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 ;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值