package org.cs.jdbc;import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;public class BaseConn {
public static void main(String[] args) throws Exception {
temp();
} public static void temp() throws SQLException {
String sql = "select * from temp";
ResultSet rs = null;
Statement st = null;
Connection conn = null;
sql = "select * from temp";
try {
conn = JDBCSing.getConnection();
st = conn.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2));
}
} finally {
JDBCSing.closes(rs, st, conn);
}
}
}
***********************************
package org.cs.jdbc;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;public final class JDBCSing {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/emp";
private static String user = "root";
private static String password = ""; private JDBCSing() {
} private static JDBCSing instance = null; public static JDBCSing getInstance() {
if (instance == null) {
synchronized (JDBCSing.class) {
if (instance == null)
instance = new JDBCSing();
}
}
return instance;
} static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
} public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
} public static void closes(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
*******************************

解决方案 »

  1.   

    不懂你贴这些找骂的代码什么意思。你的代码起码有以下错误
    1.既然JDBCSing用了单例模式,那么除了getInstance之外的其他方法和属性应该都不是static的!!!!!
    2.JDBCSing用了懒汉式单例,双重检查机制在java里是没有效果的!!!!!!
    3.closes这个方法莫名其妙!!!!!套那么多层trycatch,是嫌速度还不够慢????
    try {
        rs.close();
    } catch(SQLException e) {}
    try {
        st.close();
    } catch(SQLException e) {}
    try {
        conn.close();
    } catch(SQLException e) {}
    这样的结构放在finally里就可以了,不用套那么多层!!!!!
    4.既然是常量,居然都没有final关键字,而且命名没有全部大写!!!!!
    5.shit,注释为0!!!!!!!
      

  2.   

      如果我用static模式怎么样呢?