我有 2 个类 ConnectionUtil、DemoResultSet。问题是当我运行insert 2 times()时,只有 1 条记录被插入到数据库中。第二次插入创建错误:"Error:The connection is closed."
。所以当我取消注释时close() statement
。它运行良好。我不知道有什么问题。任何人都给我一些想法
public class ConnectionUtil {
private static String url = "jdbc:sqlserver://localhost:1433;databaseName=Northwind";
private static String username = "user";
private static String pw = "pass";
private static Connection conn = null;
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(ConnectionUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static Connection getConnection() {
if (conn == null) {
try {
conn = DriverManager.getConnection(url, username, pw);
} catch (SQLException ex) {
Logger.getLogger(ConnectionUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
return conn;
}
}
public class DemoResultSet {
private static ResultSet rs = null;
private static Connection conn = null;
public static void initialize() {
try {
conn = ConnectionUtil.getConnection();
Statement statement = conn.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE );
String sql = "select CategoryID, CategoryName from Categories";
rs = statement.executeQuery(sql);
} catch (SQLException ex) {
Logger.getLogger(DemoResultSet.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
initialize();
insert();
insert();
}
public static void insert() {
try {
rs.moveToInsertRow();
rs.updateString("CategoryName", "Test C1008G3");
rs.insertRow();
System.out.println("Inserted");
conn.close(); //uncomment it's okay
} catch (SQLException ex) {
System.out.println("Error:" + ex.getMessage());
}
}
}