JDBC 连接数据库
import java.sql.*;
public class DBUtils {
public static final String Driver="com.mysql.jdbc.Driver";
public static final String URL="jdbc:mysql://localhost:3306/xxx?characterEncoding=utf-8";
/*格式:jdbc:driver://host_name/db_name
前两个分别为主协议和子协议,不可省略
如果不选择主机,默认值为localhost;可以不选择默认数据库;不应省略任何斜杠
可以简写为:jdbc:mysql:///
*/
public static final String USER="xxx";//xxx表示哦用户名,一般为root
public static final String PASSWORD="xxx";//xxx表示数据库密码
private static Connection conn=null;
/**
* 加载MySQL驱动并获取数据库连接
* @return Connection
* @throws Exception
*/
public static Connection getConnection() throws Exception{
Class.forName(Driver).getDeclaredConstructor().newInstance();//对于Connector/J,驱动程序名称是名为Driver的字符串内容(开头有设置)
/*
即使不调用newInstance(),也应该可以注册驱动程序(详见MySQL经典实例 一书)
jdk9开始弃用了newInstance(),代码应修改为:getDeclaredConstructor().newInstance()
*/
conn=DriverManager.getConnection(URL,USER,PASSWORD);
return conn;
}
/**
* 关闭数据库连接
* @throws Exception
*/
public static void closeConnection()throws Exception{
if(conn!=null&&conn.isClosed()){
conn.close();
conn=null;
}
}
/**
* 使用Statement接口实行更新操作,其还可用于执行DDL,DCL,DML语句
* @param sql
* @return
* @throws Exception
*/
public int executeUpdate(String sql) throws Exception{
conn=getConnection();
Statement st=conn.createStatement();
int r=st.executeUpdate(sql);
closeConnection();
return r;
}
/**
* 使用PreparedStatement(Statement子接口)实行更新操作
* 该接口允许数据库预编译SQL语句,以后无须再传入SQL语句,只需要改变命令参数
* 避免数据库每次编译语句,因此性能更好
* @param sql
* @param obj
* @return
* @throws Exception
*/
public static int executeUpdate(String sql,Object...obj) throws Exception{
conn=getConnection();
PreparedStatement pst=conn.prepareStatement(sql);
if(obj!=null&&obj.length>0){
for (int i = 0; i <obj.length ; i++) {
pst.setObject(i+1,obj[i]);
}
}
int r=pst.executeUpdate();
closeConnection();
return r;
}
public static ResultSet executeQuery(String sql,Object...obj) throws Exception{
conn=getConnection();
PreparedStatement pst=conn.prepareStatement(sql);
if(obj!=null&&obj.length>0){
for (int i = 0; i <obj.length ; i++) {
pst.setObject(i+1,obj[i]);
}
}
ResultSet rs=pst.executeQuery();
return rs;
}
public static boolean queryLogin(String name,String password) throws Exception{
String sql="select name from t_user where name=? and password=?";
ResultSet rs=executeQuery(sql,name,password);
if(rs.next()){
return true;
}
return false;
}
}