JDBC——小结
基本代码逻辑
Properties properties = new Properties();
String path = BaseDao.class.getClassLoader().getResource("jdbc.properties").getPath(); //maven工程路径问题
【1】加载配置文件
//加载配置文件
properties.load(new FileInputStream(new File(path)));
DRIVER = properties.getProperty("DRIVER"); //获取驱动器完整包名 com.sql.jdbc.driver
URL = properties.getProperty("URL");
USER = properties.getProperty("USER");
PASSWD = properties.getProperty("PASSWD");【2】加载驱动
Class.forName(DRIVER);
//其本质:registeredDrivers.addIfAbsent(new DriverInfo(driver, da));
【3】获取连接
connection = DriverManager.getConnection(URL, USER, PASSWD);
=================================================
//两种执行方式
-Statement
Statement statement = connection.createStatement();
【1】查询操作
ResultSet resultSet = statement.executeQuery("select * from emp"
+ " where empno = "+empno);while(resultSet.next()){
//支持列明,列位置[从1开始],列别名
int eno = resultSet.getInt("empno");}
-PreparedStatement:通过设置占位符,避免sql漏洞
PreparedStatement preState = connection.prepareStatement("select * from emp"
+ " where deptno = ? and job = ?");preState.setObject(1, deptno);
preState.setString(2, job);
ResultSet resultSet = preState.executeQuery();【2】插入数据操作
connection = DriverManager.getConnection(url, user, passwd);
PreparedStatement ps = connection.prepareStatement("insert into `dept` values(?,?,?)");
ps.setObject(1, 60);
ps.setObject(2, "Tech_DA");
ps.setObject(3,"Shenzhen");
int i = ps.executeUpdate(); // 返回值>0:擦入数据成功【3】删除操作
connection = DriverManager.getConnection(url, user, passwd);
PreparedStatement ps = connection.prepareStatement("delete from `dept` where `deptno` = ?");
ps.setObject(1, 60);
int i = ps.executeUpdate();【4】更新数据
connection = DriverManager.getConnection(url, user, passwd);
PreparedStatement ps = connection.prepareStatement("update dept set dname = ? where deptno = 60");
ps.setObject(1, "DataCenter");
int i = ps.executeUpdate();
【5】批量添加
PreparedStatement ps = connection.prepareStatement("insert into `dept` values(?,?,?)");
for(int dept=50;dept<100;dept+=10){
ps.setObject(1, dept);
ps.setObject(2, "Product");
ps.setObject(3,"beijing");
ps.addBatch();
}
int[] flags = ps.executeBatch();【6】数据提交
connection.setAutoCommit(false); //设置取消自动提交
PreparedStatement ps = connection.prepareStatement("insert into `dept` values(?,?,?)");
ps.setObject(1, 60);
ps.setObject(2, "Tech_DA");
ps.setObject(3,"Shenzhen");
int i = ps.executeUpdate(); //执行sql语句
System.out.println(i);
if (i==1) {
int res = 1/0;
connection.commit(); //提交
}
进一步封装查询
-queryScottBypar()
StringBuilder sql = new StringBuilder(); // 存放操作指令字符串
sql.append("select deptno , dname, loc from dept where 1=1 ");
//动态组装,添加条件
if (dept!=null) {
if (dept.getDeptno()!=null) {
sql.append(" and deptno = ?");
}}
ps = con.prepareStatement(sql.toString());
if (dept!=null) {
if (dept.getDeptno()!=null) {
ps.setObject(++index, dept.getDeptno());
}}
添加对应得jar包 && maven依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>