当对数据库进行相关操作时,首先要连接数据库,如果每对数据库进行一次操作就要连接一次,就会有大量的代码重复,效率变低,并且浪费资源。而Java是面向对象的语言,三大特性之一:封装,就很好的解决了这个问题。将大量重复的操作放在一个工具类中,当需要使用这些操作时只需要调用这个工具类里的方法即可。
连接数据库
完整代码:
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String user;
private static String password;
private static String url;
private static String driver;
static {
FileInputStream fis = null;
try {
//1.读取配置文件
//1.1创建Properties对象
Properties p = new Properties();
//1.2创建流
fis = new FileInputStream("jdbc.properties");
//1.3调用方法
p.load(fis);
//1.4读取内容
user = p.getProperty("user");
password = p.getProperty("password");
url = p.getProperty("url");
driver = p.getProperty("driver");
System.out.println(user+" "+password+" "+url+" "+driver);
}catch (Exception e){
e.printStackTrace(); //打印错误信息
//终止程序运行(将编译时异常转换成运行时异常)
throw new RuntimeException(e.getMessage());
}finally {
if(fis != null){
try {
fis.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
//获取Connection对象
public static Connection getConnection() {
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
//关闭资源
public static void close(PreparedStatement ps, Connection connection) {
if (ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
其中关于配置文件的相关内容在:配置文件简述
之后再进行数据库连接时,只需要JDBCUtils.getConnection()调用即可
PreparedStatement的百度百科
由以上链接可以得出,PreparedStatement对象已经预编译过,创建对象的方式为:
PreparedStatement ps = connection.PrepareStatement(sql); String sql = "insert into 表名(字段名1,字段名2,...) values(?,?,...)"; //?表示占位符
每个“?”的值必须在执行前通过setXXX()方法被提供
//举例: 有一个student表,表中有两个字段分别是:id int,name varchar(20) sql语句为 insert into student(id,name),values(?,?) 则,ps.setInt(1,1001); //表示给第一个?赋值1001,即id = 1001 ps.setString(2,"Jerry"); //表示给第二个?赋值Jerry,即name = Jerry执行sql语句
数据库查找操作
ps.executeUpdate() //对sql语句是增,删,改的操作执行 ps.executeQuery() //对数据库执行查找操作完整代码
Connection connection = JDBCUtils.getConnection(); String sql = "insert into 表名(字段名1,字段名2,...) values(?,?,...)"; //sql = "update 表名 set 字段名1 = ? where 字段名2=?"; //sql = "delete from 表名 [where 字段名1=?]"; PreparedStatement ps = connection.PrepareStatement(sql); ps.setXXX(parameterIndex,x); //根据需求编写 ps.executeUpdate(); //关闭资源 -- 相当于还回去 JDBCUtils.close(ps,connection);



