import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQL {
private static final String name = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://127.0.0.1:3306/";
//数据库名称
private static final String database = "book";
//用户名及密码
private static final String user = "root";
private static final String password = "";
protected Connection connect = null;
protected Statement statement = null;
{
try {
// 加载MySQL驱动
Class.forName(name);
// 通过DriverManger获取数据库连接
connect = DriverManager.getConnection(url + database, user, password);
// 通过Connection对象创建Statement对象
statement = connect.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 执行SQL查询语句
public ResultSet sqlQuery(String select) {
ResultSet res = null;
try {
res = statement.executeQuery(select);
} catch (SQLException e) {
e.printStackTrace();
}
return res;
}
// 执行SQL更新语句
public void sqlUpdate(String update) {
try {
statement.executeUpdate(update);
} catch (SQLException e) {
e.printStackTrace();
}
}
// 关闭连接
public void sqlClose() {
try {
statement.close();
connect.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
MySQL驱动下载地址:http://dev.mysql.com/downloads/connector/j/
热门评论
不关闭结果集吗?求高人指点
一定要养成随手关连接的习惯啊!
先关statement