JDBC
JDBCUtil
依赖Jar包 ==》 mysql-connector-java-5.1.8.jar
public class JDBCUtil {
//因为每次操作都需要连接数据库这一步骤 所以我们可以把这部分内容封装成工具类
//书写一个方法 方法的返回类型 connection对象
//把参数声明常量
public static final String JDBCDRVIER = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/kkb";
public static final String USER = "root";
public static final String PASSWORD = "123";
//注册驱动 放到静态代码块中 只注册一次
static {
try {
Class.forName(JDBCDRVIER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
return DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//关闭资源
public static void closeJDBC(Connection c1, Statement s1, ResultSet rs) {
if (c1 != null) {
try {
c1.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (s1 != null) {
try {
s1.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
四大对象
-
Connection
-
Statement
执行静态sql语句,每次执行语句数据库都要执行sql的编译操作,效率低
并且拼接字符串麻烦
还不能防止sql注入
-
PreStatement
动态sql语句,预编译sql语句,效率高
防止sql注入
字符串拼接简单
-
ResultSet
例子
字符串 用 ‘ ’ 单引号
数字直接写
拼接
? ?
pstm.setInt(1,1);
pstm.setString(1,"xxx");
- 查
Connection c1 = JDBCUtil.getConnection();
String sql = "select*from score";
PreparedStatement pstm = c1.prepareStatement(sql);
ResultSet rs = pstm.executeQuery();
while (rs.next()) { ####
System.out.println(rs.getString("c_name")); ###
System.out.println(rs.getString(2)); ###
}
JDBCUtil.closeJDBC(c1, pstm, rs);
- 删
Connection c1 = JDBCUtil.getConnection();
String name = "alex";
String pwd = "alex123";
String sql = "delete from userinfo where id=2";
PreparedStatement pstm = c1.prepareStatement(sql);
int rs =pstm.executeUpdate();
JDBCUtil.closeJDBC(c1, pstm,null);
- 改
Connection c1 = JDBCUtil.getConnection();
String name = "alex";
String pwd = "alex123";
String sql = "update userinfo set username='tom1' where id=2";#
PreparedStatement pstm = c1.prepareStatement(sql);#
int rs =pstm.executeUpdate(); #
JDBCUtil.closeJDBC(c1, pstm,null);
- 增
Connection c1 = JDBCUtil.getConnection();
String name = "alex";
String pwd = "alex123";
String sql = "insert into userinfo (username,password)values('tom','bob')"; #
PreparedStatement pstm = c1.prepareStatement(sql); #
int rs =pstm.executeUpdate();#
JDBCUtil.closeJDBC(c1, pstm,null);
实体类
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
返回单个数据
UserBean u = new UserBean(); ## 实体类
Connection c1 = JDBCUtil.getConnection();
String sql = "select*from userinfo where id = ?";
PreparedStatement pstm = c1.prepareStatement(sql);
pstm.setInt(1,5);
ResultSet rs = pstm.executeQuery();
if(rs.next()){
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
System.out.println(u);
System.out.println(u.getUsername());
}
JDBCUtil.closeJDBC(c1,pstm,rs);
返回多个数据
集合泛型
Connection c1 = JDBCUtil.getConnection();
String sql = "select*from userinfo";
PreparedStatement pstm = c1.prepareStatement(sql);
ResultSet rs = pstm.executeQuery();
List<UserBean> list = new ArrayList<UserBean>(); ####
while (rs.next()){
UserBean u = new UserBean();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
list.add(u);
}
System.out.println(list);
JDBCUtil.closeJDBC(c1,pstm,rs);
事务操作
- 获取链接
- 开启事务
- 获取preparedStatement
- 完成操作
- 有问题 回滚
- 无问题 提交
- finally 关闭资源
Connection c1 = null;
PreparedStatement pstm = null;
int rs = 0;
int rs1 = 0;
try {
c1 = JDBCUtil.getConnection();
c1.setAutoCommit(false); ####
String sql = "update userinfo set username=? where id=7";
pstm = c1.prepareStatement(sql);
pstm.setString(1, "alex");
rs = pstm.executeUpdate();
} catch (Exception e) {
System.out.println("失败 正在回滚");
c1.rollback(); #####
}
c1.commit(); ########
JDBCUtil.closeJDBC(c1, pstm, null);
}
连接池(用法一样)
C3P0(用的多)
c3p0-0.9.1.2.jar
c3p0-config.xml(放src下)
封装工具类
public class C3P0Utils {
//找的是默认配置文件中的数据源信息
private static ComboPooledDataSource cpds = new ComboPooledDataSource();
//返回建立连接对象
public static Connection getConnection() throws SQLException, SQLException {
return cpds.getConnection();
}
//返回dataSource 数据源 DButils
public static DataSource getDS() {
return cpds;
}
}
例子(同JDBCUtil)
public class C3P0Demon {
public static void main(String[] args) throws SQLException {
Connection c1 = C3P0Utils.getConnection();
String sql = "select*from userinfo";
PreparedStatement pstm =c1.prepareStatement(sql);
ResultSet rs = pstm.executeQuery();
while (rs.next()){
System.out.println(rs.getString("username"));
}
}
}
DBCP
导入两个jar包
commons-pool-1.5.6.jar
commons-dbcp-1.4.jar
配置文件
db.properties
url=jdbc:mysql:///kkb
username=root
password=123
driverClassName=com.mysql.jdbc.Driver
封装工具类
public class DBCPUtils {
private static DataSource dSource=null;
static {
//第一步 得到db文件
InputStream is=DBCPUtils.class.getClassLoader().
getResourceAsStream("db.properties");
Properties p1=new Properties();
//加载文件
try {
p1.load(is);
dSource=BasicDataSourceFactory.createDataSource(p1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//返回connection方法
public static Connection getConnection() {
try {
return dSource.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//返回数据源
public static DataSource getDarSource() {
return dSource;
}
}
DBUtils
对JDBC的封装
commons-dbutils-1.4.jar
c3p0-0.9.1.2.jar
mysql-connector-java-5.1.8.jar
结合 c3p0 或 dbcp 来使用
## UserBean是 实体类
QueryRunner qr = new QueryRunner(C3P0Utils.getDS());
String sql="select*from userinfo ";
ResultSetHandler rsh;
UserBean c1 = qr.query(sql,new BeanHandler<UserBean>(UserBean.class)); ## 单个是 BeanHandler
## 拼接参数
UserBean c1 = qr.query(sql,new BeanHandler<UserBean>(UserBean.class),参数);
## 多行
List<UserBean> c1 = qr.query(sql,new BeanListHandler<UserBean>(UserBean.class));
System.out.println(c1);
## MapHandler() 单行 返回Map类型
##MapListHandler() 多行