可以将获取连接的部分封装起来,通过读取配置文件来获得Connection对象。
本例子的配置文件为src/jdbc.properties,封装类为jdbcUtils
请注意封装类的写法
为什么用静态块
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;
import com.mysql.jdbc.Driver;
//封装连接
//通过配置文件 jdbc.properties
public class jdbcUtils {
private static final String DRIVERCLASS;
private static final String URL;
private static final String USERNAME;
private static final String PASSWORD;
static{
DRIVERCLASS = ResourceBundle.getBundle("jdbc").getString("driverClass");
URL = ResourceBundle.getBundle("jdbc").getString("url");
USERNAME = ResourceBundle.getBundle("jdbc").getString("username");
PASSWORD = ResourceBundle.getBundle("jdbc").getString("password");
}
//在静态代码块中,可以保证驱动不用重复加载
static{
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception{
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
return con;
}
}
CRUD
文件关闭操作按上次比较完整的改正
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
import cn.itcast.util.jdbcUtils;
import com.mysql.jdbc.Driver;
public class jdbcDemo5 {
//按id查找,后面可以给一个id形参
public void findById() throws Exception{
String sql = "select * from user where id=1";
Connection con = jdbcUtils.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
rs.next();//需要将光标移向下一行
System.out.println(rs.getString("password"));
rs.close();
st.close();
con.close();
}
//添加操作
public void addTest() throws Exception{
String sql = "insert into user values(null,'jjohn','123','123@qq.com')";
Connection con = jdbcUtils.getConnection();
Statement st = con.createStatement();
int row = st.executeUpdate(sql);
System.out.println(row);
st.close();
con.close();
}
//删除操作
public void deleteTest() throws Exception{
String sql = "delete from user where id=3";
Connection con = jdbcUtils.getConnection();
Statement st = con.createStatement();
st.executeUpdate(sql);
st.close();
con.close();
}
//修改操作
public void updateTest() throws Exception{
String sql = "update user set password='456' where id=3";
Connection con = jdbcUtils.getConnection();
Statement st = con.createStatement();
int row = st.executeUpdate(sql);
System.out.println(row);
st.close();
con.close();
}
}
网友评论