数据库连接_留着以后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;
}
}