JDBC连接的封装函数

来源:互联网 发布:海信液晶电视连接网络 编辑:程序博客网 时间:2024/05/16 23:34
import java.sql.*;//封装数据库操作相关函数public class DB {//拿到Connectionpublic static Connection getConnection(){Connection conn = null;try {Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=****");} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return conn;}//拿到Statementpublic static Statement getStatement(Connection conn){Statement sttm = null;try {sttm = conn.createStatement();} catch (SQLException e) {e.printStackTrace();}return sttm;}//拿到ResultSetpublic static ResultSet getResultSet(Statement sttm,String sql){ResultSet rs = null;try {rs = sttm.executeQuery(sql);} catch (SQLException e) {e.printStackTrace();}return rs;}//关闭相关的连接public static void close(Connection conn){try {if(conn != null){conn.close();conn = null;}} catch (SQLException e) {e.printStackTrace();System.out.println("关闭失败");}}public static void close(Statement sttm){try{if(sttm != null){sttm.close();sttm = null;}}catch(SQLException e){e.printStackTrace();}}public static void close(ResultSet rs){try{if(rs != null){rs.close();rs = null;}}catch(SQLException e){e.printStackTrace();}}}

原创粉丝点击