直接上代码
package com.wanghuan.getDataBase;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.wanghuan.util.PrintTest;
/**
* JDBC java连接数据库,对数据库进行操作
*
* @author HP
*
*/
public class Dao {
private String number;
static Dao dao = new Dao();
public static Dao getDao() {
if (dao != null) {
return dao;
}else {
return new Dao();
}
}
// 静态代码块
static {
// 1、加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
PrintTest.print("加载驱动失败!");
e.printStackTrace();
}
}
/**
* 获取连接
*
* @return
*/
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost/shopping_data", "root", "admin");
} catch (SQLException e) {
PrintTest.print("获取连接失败!");
e.printStackTrace();
}
return con;
}
/**
* 获取一个连接的实例
*
* @param sql
* @return
*/
public Statement getStatement() {
Statement sta = null;
try {
sta = this.getConnection().createStatement();
} catch (SQLException e) {
PrintTest.print("获取连接实例失败!");
e.printStackTrace();
}
return sta;
}
/**
* 更改数据
*
* @param sql
*/
public void setData(String sql) {
try {
this.getStatement().executeUpdate(sql);
} catch (SQLException e) {
PrintTest.print("更改数据失败!");
e.printStackTrace();
}
}
/**
* 查看数据
*
* @param sql
* @return
*/
public ResultSet seeData(String sql) {
ResultSet re = null;
try {
re = this.getStatement().executeQuery(sql);
} catch (SQLException e) {
PrintTest.print("获取ResultSet失败!");
e.printStackTrace();
}
return re;
}
/**
* 释放资源
*/
public void close(Connection con, PreparedStatement sta, ResultSet re) {
try {
if (re != null && !re.isClosed()) {
re.close();
re = null;
}
if (sta != null && !sta.isClosed()) {
sta.close();
sta = null;
}
if (con != null && !con.isClosed()) {
con.close();
con = null;
}
} catch (Exception e) {
System.err.println("关闭连接失败!");
e.printStackTrace();
}
}
/**
* 修改number
* @param number
*/
public void setNumber(String number) {
this.number = number;
}
/**
* 查看number
* @return
*/
public String getNumber() {
return number;
}
}