JDBC工具类
封装了对数据库进行查询与增删改的方法,采用单例模式。
public class MyDB {
private static Connection conn;
private static PreparedStatement ps;
private static ResultSet rs;
private static final String url = "jdbc:mysql://localhost:3306/库名?characterEncoding=utf8";
private static final String username = "root";
private static final String password = "root";
private static MyDB myDB;
private MyDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
System.out.println("数据库初始化失败");
}
}
public static MyDB getMyDB() {
if (myDB == null) {
myDB = new MyDB();
}
return myDB;
}
public ResultSet getQuery(String sql, Object... args) {
try {
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
System.out.println("查询异常");
}
return rs;
}
public boolean getUpdate(String sql, Object... args) {
boolean flag = false;
try {
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
flag = ps.executeUpdate() >= 1;
} catch (Exception e) {
e.printStackTrace();
System.out.println("增删改异常");
}
return flag;
}
public void close() {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null && !ps.isClosed()) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
简单应用
public class Test {
static MyDB myDB = MyDB.getMyDB();
private static void method1(String name, String pwd) {
String sql = "select * from user where name=? and password=?";
ResultSet rs = null;
rs = myDB.getQuery(sql, name, pwd);
try {
if (rs.next()) {
System.out.println("登陆成功");
} else {
System.out.println("登录失败");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
myDB.close();
}
}
public static void method2(int id) {
String sql = "delete from user where id = ?";
if (myDB.getUpdate(sql, id)) {
System.out.println("增删改成功");
}
myDB.close();
}
}
|