我有2個類ConnectionUtil,DemoResultSet。問題是當我運行插入2次()。然後只有1條記錄被插入數據庫。第二個插入創建錯誤:"Error:The connection is closed."
。所以當我取消close() statement
。它運行得很好。我不知道有什麼麻煩。任何人都給我一些想法Java jdbc無法插入數據庫
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());
}
}
}
我按照你的說法做了。但是我做錯了 – haind
你會得到什麼錯誤? – Stultuske
它顯示:2013年10月1日下午4點34分20秒ResultSetDemo.DemoResultSet初始化 錯誤:連接已關閉。 SEVERE:null – haind