求助!急!
com.microsoft.sqlserver.jdbc.SQLServerException: 该连接已关闭。
com.microsoft.sqlserver.jdbc.SQLServerException: 该连接已关闭。
at com.microsoft.sqlserver.jdbc.
SQLServerException.makeFromDriverError(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.checkClosed(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.createStatement(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.createStatement(Unknown Source)
at task.MyDB.execute(MyDB.java:34)
at task.DBTest.<init>(DBTest.java:9)
at task.DBTest.main(DBTest.java:12)
代码如下:
package task;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import
java.sql.SQLException;
import java.sql.Statement;
public class MyDB {
private Connection con;
private ResultSet rs;
private int n;
//连接数据库
public Connection getConnection(String driverName, String URL, String userName, String password){
try {
Class.forName(driverName);
con=DriverManager.getConnection(URL, userName, password);
con.close();
} catch (
ClassNotFoundException e) {
e.printStackTrace();
} catch (
SQLException e) {
e.printStackTrace();
}
return con;
}
/*执行SQL语句,有可能是select、insert、update、delete语句中的任何一个,要对参数sql先进行判断,
再分类处理:如为查询语句,需将结果集中的所有行、列数据显示输出;若是增删改语句,
除执行对应操作外,还要输出“增加(修改、删除)xx条记录”。*/
public void execute(Connection connString, String sql){
try {
Statement st=connString.createStatement();
if(sql.startsWith("select")){
rs=st.executeQuery(sql);
ResultSetMetaData rsmd=rs.getMetaData();
n=rsmd.getColumnCount();
while(rs.next()){
for(int i=1;i<n;i++)
System.out.print(rs.getObject(i)+" ");
}
}else if(sql.startsWith("insert")){
int m=st.executeUpdate(sql);
System.out.println("增加"+m+"条记录。");
}else if(sql.startsWith("update")){
int m=st.executeUpdate(sql);
System.out.println("修改"+m+"条记录。");
}else{
int m=st.executeUpdate(sql);
System.out.println("删除"+m+"条记录。");
}
rs.close();
st.close();
connString.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package task;
import java.sql.Connection;
import java.sql.SQLException;
public class DBTest {
MyDB mydb=new MyDB();
public DBTest(String driverName, String URL, String userName, String password,String sql){
Connection conn=mydb.getConnection(driverName, URL, userName, password);
mydb.execute(conn, sql);
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DBTest("com.microsoft.sqlserver.jdbc.SQLServerDriver","jdbc:sqlserver://172.16.107.88:1433;DatabaseName=qin;","SQL","SQL","select * from Students");
}
}
麻烦大家帮帮忙!!!
------解决方案--------------------链接关闭太早了 在查询后关闭!