I have 2 classes ConnectionUtil, DemoResultSet. The problem is when I run insert 2 times().Then just only 1 record is inserted to database. The second insert create error: "Error:The connection is closed.". So when I uncomment close() statement. It run nice. I don't know what is the trouble. Anyone give me some idea
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());
}
}
}