日期:2014-05-20  浏览次数:20840 次

JAVA 连接数据库问题 请高手指点
请问下面这段程序应该在什么时候用 conn.close; 请指点!


package shujuzhuanhuan;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ZhengfaLiang {
public static void main(String args[])
{
String STTM = "";
String ENTM = "";
String STCDb = "";
String NAME = "";

Connection conn;
Statement state;
Statement state_1;
ResultSet res;
ResultSet res_1;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:ccc", "", "");
state = conn.createStatement();
res = state
.executeQuery("SELECT * FROM ZONG_HE WHERE leixing='DAYEV'");


  while (res.next()) {

STCDb = res.getString(1);
System.out.println(STCDb); //测试
NAME = res.getString(8);
STTM = res.getString(3);
ENTM = res.getString(4);
// System.out.println(" ffffffffffffffffffffffffffffff");
FileWriter fw = new FileWriter( // 创建新文件
"e://workshengchengshuju//ri_zhengfa_liang//"
+ STCDb + ".ev24");
BufferedWriter bw = new BufferedWriter(fw);

bw.write("STCD=" + STCDb);
bw.newLine();
bw.write("NAME=" + NAME);
bw.newLine();
bw.write("TYPE = EV");
bw.newLine();
bw.write("DIME = L");
bw.newLine();
bw.write("UNIT = MM");
bw.write("STTM =" + STTM);
bw.newLine();
bw.write("ENTM =" + ENTM);
bw.newLine();
bw.write("年" + " " + "月" + " " + "日"
+ " " + "DYE");
//conn.close();

// 重建于表ST_RVAV_R的连接
state_1 = conn.createStatement();

res_1 = state_1
.executeQuery("SELECT * FROM ST_DAYEV_R WHERE STCD='"
+ STCDb + "' ORDER by TM");

// System.out.println(res_1.next()); //测试
while (res_1.next()) {

String shuju = res_1.getString(4);
String zongchangriqi = res_1.getString(2);
String[] str = zongchangriqi.split("-");
String[] ri = str[2].split(" ");

try {

bw.newLine();
bw.write(str[0] + " " + str[1] + " "
+ ri[0] + " " + shuju);
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bw.flush();

// System.out.println(STCDb + " " + NAME + " " + STTM);
// System.exit(0);
}
// conn.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// bw.close();
}

}


------解决方案--------------------
在try后加一个finally,在它里面关吧,当然要记得判断是否为空和抛异常。