MYSQL数据访问工具类DBUtils

来源:互联网 发布:大数据基金净值 编辑:程序博客网 时间:2024/05/24 01:40
package com.msun.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class DBUtil {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/learnjsp";
private static String user = "root";
private static String pwd = "";
private static Connection conn;
private static PreparedStatement pstmt;
private static ResultSet rs;
// 打开数据库连接
public static Connection getCon() {
if (conn == null) {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
return conn;
}

//查询数据库
public static ResultSet query(String sql){
conn = getCon();
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
//增加信息
public static boolean add(String sql){
boolean flag = false;
try{
conn = getCon();
pstmt = conn.prepareStatement(sql);
int count = pstmt.executeUpdate();
if(count > 0){
flag = true;
}
}catch(SQLException e){
e.printStackTrace();
}
return flag;
}
//更新数据库信息
public static boolean update(String sql){
boolean flag = false;
try{
conn = getCon();
pstmt = conn.prepareStatement(sql);
int count = pstmt.executeUpdate();
if(count > 0){
flag = true;
}
}catch(SQLException e){
e.printStackTrace();
}
return flag;
}
//删除一条数据库信息
public static boolean delete(String sql){
boolean flag = false;
try{
conn = getCon();
pstmt = conn.prepareStatement(sql);
int count = pstmt.executeUpdate();
if(count > 0){
flag = true;
}
}catch(SQLException e){
e.printStackTrace();
}
return flag;
}
// 关闭数据库
public static void closeConn() {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pstmt != null){
try{
pstmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
if(conn != null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}

原创粉丝点击