- package com.util;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- /**
- * 封装数据常用操作
- *
- * @author 刘鹏
- *
- */
- public class DbUtil {
- /**
- * 取得Connection
- *
- * @return
- */
- public static final String DBDRIVER="com.mysql.jdbc.Driver";
- public static final String DBURL="jdbc:mysql://localhost:3306/lp";
- public static final String DBUSER="root";
- public static final String DBPASS="mysqladmin";
- public static Connection conn = null;
- public static Statement pstm = null;
- public static PreparedStatement pstmt = null;
- /**
- * 取得数据库连接
- * @return
- */
- public static Connection getConnection(){
- try{
- Class.forName(DBDRIVER);
- }catch(ClassNotFoundException e){
- e.printStackTrace();
- }
- try{
- conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
- }catch(SQLException e){
- e.printStackTrace();
- }
- return conn;
- }
- /**
- * 数据库操作
- * @return
- */
- public static Statement getStatement(Connection con){
- //con = DbUtil.getConnection();
- try {
- if (con != null) {
- pstm = con.createStatement();
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return pstm;
- }
- /**
- * 数据库操作
- * @return
- */
- public static PreparedStatement getPstmt(Connection con,String sql) {
- //con = DbUtil.getConnection();
- if (con != null) {
- try {
- pstmt = conn.prepareStatement(sql);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- return pstmt;
- }
- /**
- * 查询操作,基于PreparedStatement接口
- * @param conn
- * @param sql
- * @return
- */
- public static ResultSet getResultSet(Connection conn,String sql){
- pstmt = DbUtil.getPreparedStatement(conn, sql);
- try {
- rs = pstmt.executeQuery();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return rs;
- }
- /**
- * 关闭数据库连接
- * @param conn
- */
- public static void close(Connection conn){
- if(conn!=null){
- try{
- conn.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- }
- /**
- * 关闭数据库操作Statement
- * @param stmt
- */
- public static void close(Statement stmt){
- if(stmt!=null){
- try{
- stmt.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- }
- /**
- * 关闭数据库操作PreparedStatement
- * @param pstmt
- */
- public static void close(PreparedStatement pstmt){
- if(pstmt!=null){
- try{
- pstmt.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- }
- /**
- * 关闭数据库查询
- * @param rs
- */
- public static void close(ResultSet rs){
- if(rs!=null){
- try{
- rs.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- }
- /**
- * 主方法用于测试
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- System.out.println(DbUtil.getConnection());
- }
- }
Mysql连接数据库封装类
最新推荐文章于 2022-05-05 07:57:04 发布