概览
JDBC-API代码实现部分
需要将lib文件中的外来的jar包右键【Build Path】-->【Configure Build Path...】
-->【Libraries】--> 【add JARs...】,然后可以在Referenced Libraries中看到
package basic_steps;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
public class MyTest {
public static void main(String[] args) throws Exception {
// 1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
// 3.建立通道
Statement st = conn.createStatement();
// 4.定义sql
String sql = "select * from student";
// 5.执行sql
ResultSet rs = st.executeQuery(sql);
// 6.处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
Date birthday = rs.getDate("birthday");
System.out.println(id + "\t" + name + "\t" + age + "\t" + birthday);
}
// 7.释放资源
rs.close();
st.close();
conn.close();
}
}
单元测试+CRUD
crud:增加(Create)、读取查询(Retrieve)、更新(Update)和删除(Delete)
给项目添加单元测试,右键项目【Build Path】--> 【add Libraries...】--> 【JUnit】
选junit4和5都行,然后Finish
用单元测试写一个jdbc读表代码吧
package basic_steps;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
public class JdbcTest {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
//用单元测试,不写主方法了
@Test
public void test1() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root","root");
st = conn.createStatement();
String sql = "select * from student";
rs = st.executeQuery(sql);
while(rs.next()) {
System.out.println(rs.getInt("id")+"\t"+rs.getString("name")+"\t"+rs.getInt("age")+"\t"+rs.getDate("birthday"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
运行结果
然后继续在这个类里面写单元测试,查询写完了,把添加,删除,修改什么的写一下
// 添加 ,only重复的代码
@Test
public void test2() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
st = conn.createStatement();
String sql = "insert into student values(6,'时哥',23,'1996-03-20')";
int x = st.executeUpdate(sql);
System.out.println(x + "==========");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
抽取工具类
package basic_steps.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcUtil {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
// 关闭所有
public static void closeAll(ResultSet rs, Statement st, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
预处理PreparedStatement
package com.offcn.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
import org.junit.Test;
import com.offcn.utils.DateUtil;
import com.offcn.utils.JdbcUtil;
public class PreparedStatementTest {
/*
* PreparedStatement 预通道 是Statement接口的子接口
*
* */
@Test
public void test3(){ //登录
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名");
String username = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
String sql = "select * from user where username=? and password=?";
ps = conn.prepareStatement(sql);
ps.setObject(1, username);
ps.setObject(2, password);
rs = ps.executeQuery();
if(rs.next()){
System.out.println("登录成功!!!");
}else{
System.out.println("登录失败!~~~");
}
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.closeAll(rs,ps, conn);
}
}
@Test
public void test2(){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
String sql = "select * from student";
ps = conn.prepareStatement(sql);
//PreparedStatement ps2 = conn.prepareStatement(sql);
//ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getInt("id")+"\t"+rs.getString("name")+"\t"+rs.getInt("age")+"\t"+rs.getDate("birthday"));
}
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.closeAll(rs,ps, conn);
}
}
@Test
public void test1(){
Scanner sc = new Scanner(System.in);
System.out.println("请输入姓名");
String name = sc.nextLine();
System.out.println("请输入年龄:");
String age = sc.nextLine();
System.out.println("请输入生日");
String birthday = sc.nextLine();
Connection conn = null;
PreparedStatement ps = null;
try{
conn = JdbcUtil.getConnection();
//String sql = "insert into student values(null,'"+name+"',"+Integer.parseInt(age)+",'"+birthday+"')";
String sql = "insert into student values(null,?,?,?)";
ps = conn.prepareStatement(sql);
/*
ps.setString(1, name);
ps.setInt(2, Integer.parseInt(age));
ps.setDate(3, new java.sql.Date(DateUtil.stringToDate(birthday).getTime()));
//java.sql.Date() java.util.Date()
*/
ps.setObject(1, name); // 绑定?
ps.setObject(2, Integer.parseInt(age));
ps.setObject(3, DateUtil.stringToDate(birthday));
int x = ps.executeUpdate();
System.out.println(x+"......");
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.closeAll(null, ps, conn);
}
}
}
获取.properties新方法
区别于属性集合的.load()方法
package basic_steps;
import java.util.ResourceBundle;
public class TestProperties {
public static void main(String[] args) {
ResourceBundle rb = ResourceBundle.getBundle("db");
String str = rb.getString("username");
System.out.println(str);
}
}
DAO开发模式
DAO接口
package com.offcn.dao;
import java.util.Date;
import java.util.List;
import com.offcn.bean.Student;
public interface StudentDao {
public int insertStudent(Student stu);
public List<Student> findAllStudent();
public Student findStudentById(int id);
public List<Student> findStudentByName(String name);
public int updateStudent(Student stu);
public int deleteStudentById(int id);
}
DAO实现类
package com.offcn.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.offcn.bean.Student;
import com.offcn.dao.StudentDao;
import com.offcn.util.JdbcUtil;
public class StudentDaoImpl implements StudentDao {
@Override
public int insertStudent(Student stu){
Connection conn = null;
PreparedStatement ps = null;
int result = 0;
try{
conn = JdbcUtil.getConnection();
String sql = "insert into student values(null,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setObject(1, stu.getName());
ps.setObject(2, stu.getAge());
ps.setObject(3, stu.getBirthday());
result = ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.closeAll(null, ps, conn);
}
return result;
}
@Override
public List<Student> findAllStudent() {
List<Student> list = new ArrayList<Student>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
String sql = "select * from student";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
Student stu = new Student();
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
stu.setAge(rs.getInt("age"));
stu.setBirthday(rs.getDate("birthday"));
list.add(stu);
}
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.closeAll(rs,ps,conn);
}
return list;
}
@Override
public Student findStudentById(int id) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Student stu = null;
try{
conn = JdbcUtil.getConnection();
String sql = "select * from student where id=?";
ps = conn.prepareStatement(sql);
ps.setObject(1, id);
rs = ps.executeQuery();
while(rs.next()){
stu = new Student();
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
stu.setAge(rs.getInt("age"));
stu.setBirthday(rs.getDate("birthday"));
}
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.closeAll(rs,ps,conn);
}
return stu;
}
@Override
public List<Student> findStudentByName(String name) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<Student> list = new ArrayList<Student>();
try{
conn = JdbcUtil.getConnection();
String sql = "select * from student where name like ?";
ps = conn.prepareStatement(sql);
ps.setObject(1, "%"+name+"%");
rs = ps.executeQuery();
while(rs.next()){
Student stu = new Student();
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
stu.setAge(rs.getInt("age"));
stu.setBirthday(rs.getDate("birthday"));
list.add(stu);
}
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.closeAll(rs,ps,conn);
}
return list;
}
@Override
public int updateStudent(Student stu) {
Connection conn = null;
PreparedStatement ps = null;
int result = 0;
try{
conn = JdbcUtil.getConnection();
String sql = "update student set name=?,age=?,birthday=? where id=?";
ps = conn.prepareStatement(sql);
ps.setObject(1, stu.getName());
ps.setObject(2, stu.getAge());
ps.setObject(3, stu.getBirthday());
ps.setObject(4, stu.getId());
result = ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.closeAll(null, ps, conn);
}
return result;
}
@Override
public int deleteStudentById(int id) {
Connection conn = null;
PreparedStatement ps = null;
int result = 0;
try{
conn = JdbcUtil.getConnection();
String sql = "delete from student where id=?";
ps = conn.prepareStatement(sql);
ps.setObject(1, id);
result = ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.closeAll(null, ps, conn);
}
return result;
}
}
DAO测试类
package com.offcn.test;
import java.sql.Connection;
import java.util.List;
import java.util.Scanner;
import org.junit.Test;
import com.offcn.bean.Student;
import com.offcn.dao.StudentDao;
import com.offcn.dao.impl.StudentDaoImpl;
import com.offcn.util.DateUtil;
import com.offcn.util.JdbcUtil;
public class JdbcTest {
StudentDao dao = new StudentDaoImpl();
@Test
public void test6(){
Scanner sc = new Scanner(System.in);
System.out.println("请输入要删除的id");
String id = sc.nextLine();
int result = dao.deleteStudentById(Integer.parseInt(id));
if(result>0){
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
}
@Test
public void test5(){
Scanner sc = new Scanner(System.in);
System.out.println("请输入要修改的数据的id");
String id = sc.nextLine();
System.out.println("姓名修改为:");
String name = sc.nextLine();
System.out.println("年龄修改为:");
String age = sc.nextLine();
System.out.println("生日修改为");
String birthday = sc.nextLine();
Student stu = new Student();
stu.setId(Integer.parseInt(id));
stu.setName(name);
stu.setAge(Integer.parseInt(age));
stu.setBirthday(DateUtil.stringToDate(birthday));
int result = dao.updateStudent(stu);
if(result>0){
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
}
@Test
public void test4(){
Scanner sc = new Scanner(System.in);
System.out.println("请输入姓名:");
String name = sc.nextLine();
List<Student> list = dao.findStudentByName(name);
for(Student s:list){
System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getBirthday());
}
}
@Test
public void test3(){
Student s = dao.findStudentById(4);
if(s!=null){
System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getBirthday());
}else{
System.out.println("没有查到数据");
}
}
@Test
public void test2(){
List<Student> list = dao.findAllStudent();
for(Student s:list){
System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getBirthday());
}
}
@Test
public void test1(){
Scanner sc = new Scanner(System.in);
System.out.println("请输入姓名:");
String name = sc.nextLine();
System.out.println("请输入年龄:");
String age = sc.nextLine();
System.out.println("请输入生日");
String birthday = sc.nextLine();
Student stu = new Student();
stu.setName(name);
stu.setAge(Integer.parseInt(age));
stu.setBirthday(DateUtil.stringToDate(birthday));
int result = dao.insertStudent(stu);
if(result>0){
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
}
}
学生类
package com.offcn.bean;
import java.util.Date;
public class Student {
private int id;
private String name;
private int age;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}