您的位置:首页 > 数据库

数据库连接_留着以后copy

2017-05-12 09:09 169 查看

数据库连接_留着以后copy

自己写的东西,每次用到数据库都得敲一遍,懒人一个,写出来等哪天用得到直接copy。


代码块

import java.sql.*;

public class BaseDao {

private Connection conn;
private PreparedStatement ps;
private ResultSet rs;

// 获得连接
private void getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/tushuguan";
conn = DriverManager.getConnection(url, "root", "");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}

// 关闭
public void close() {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

// 更新---增加,修改,删除
public int executeUpdate(String sql, Object... objects) {
try {
this.getConnection();
ps = conn.prepareStatement(sql);
if (objects != null)// 设置参数
for (int i = 0; i < objects.length; i++) {
ps.setObject(i + 1, objects[i]);
}
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.close();
}
return -1;
}

//查询
public ResultSet executeQuery(String sql,Object...objects){
try {
this.getConnection();
ps = conn.prepareStatement(sql);
if (objects != null)// 设置参数
for (int i = 0; i < objects.length; i++) {
ps.setObject(i + 1, objects[i]);
}
return ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: