封装连接mysql数据库_Mysql连接数据库封装类

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());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值