问答详情
源自:4-3 邮件发送代码实现:用户注册功能代码实现

JDBCUtils如何写

那个JDBCUtils工具类如何写,求大神指点

提问者:Serenity_Tang 2017-06-04 08:20

个回答

  • 慕仔5194083
    2018-03-19 10:48:29

    http://img3.mukewang.com/5aaf24dc000104dd07720096.jpg这咋整?

  • Serenity_Tang
    2017-06-18 15:37:33

    谢谢你

  • 骑着蜗牛定乾坤
    2017-06-07 17:27:59

    版本1:

    import java.sql.Connection;

    import java.sql.SQLException;

    import javax.sql.DataSource;

    import com.mchange.v2.c3p0.ComboPooledDataSource;


    public class JDBCUtil {

        private static DataSource dataSource = new ComboPooledDataSource();

        public static DataSource getDataSource() {

            return dataSource;

        }

        public static Connection getConnection() throws SQLException {

            return dataSource.getConnection();

        }

    }

    版本2:

    import java.sql.Connection;

    import java.sql.DriverManager;

    import java.sql.ResultSet;

    import java.sql.SQLException;

    import java.sql.Statement;


    public class JDBCUtil1 {

        private static String url = "jdbc:mysql://localhost:3306/regist_web";

        private static String user = "root";

        private static String password = "test123";

        private JDBCUtil1() {}

    static {

            try {

                Class.forName("com.mysql.jdbc.Driver");

            } catch (ClassNotFoundException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

            }

    }

        public static Connection getConnection() {

            try {

                return DriverManager.getConnection(url, user, password);

            } catch (SQLException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            return null;

            }

        }


        public static void free(ResultSet rs,Statement st,Connection conn) {

            if(rs != null) {

                try {

                    rs.close();

                } catch (SQLException e) {

                    // TODO Auto-generated catch block

                e.printStackTrace();

                } finally {

                    if(st != null) {

                        try {

                            st.close();

                        } catch (SQLException e) {

                            // TODO Auto-generated catch block

                            e.printStackTrace();

                        } finally {

                            if(conn != null) {

                                    try {

                                        conn.close();

                                    } catch (SQLException e) {

                                        // TODO Auto-generated catch block

                                        e.printStackTrace();

                                    }

                            }

                    }

            }

        }

    }

    }

    }

    视频中用的是版本1,我用版本1在daoImpl()里有点问题,所以我用的是版本2。