(1)
/** * @author: sunshine * @description: //连接数据库 * @data: 2022/3/11 10:29 * @version: 0.1 * @since: jdk11 */ public class Test { public static void main(String[] args) { String username = "root"; String password = "root"; String url = "jdbc:mysql://127.0.0.1:3306/mydb"; String drive = "com.mysql.cj.jdbc.Driver"; Connection connection = null; try { connection = DriverManager.getConnection(url, username, password); System.out.println("连接对象"+connection); connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { try { if(connection != null) { connection.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } } } }
(2)将(1)封装到工具类
创建jdbc.properties文件
#配置连接数据库的信息 jdbc.username=root jdbc.password=root jdbc.url=jdbc:mysql://127.0.0.1:3306/mydb jdbc.driver=com.mysql.cj.jdbc.Driver
/** * @author: sunshine * @description: //将连接,释放功能封装到工具类 * @data: 2022/3/11 14:30 * @version: 0.1 * @since: jdk11 */ public class DButil { private DButil(){} private static final Properties properties; static{ properties = new Properties(); try { properties.load(new FileInputStream("src\\jdbc.properties")); } catch (IOException e) { e.printStackTrace(); } } public static Connection getMysqlConn(){ Connection connection = null; try { //手动注册驱动/服务 Class.forName(properties.getProperty("jdbc.driver")); //获得特定的DBMS对象-----建立连接 connection = DriverManager.getConnection( properties.getProperty("jdbc.url"), properties.getProperty("jdbc.username"), properties.getProperty("jdbc.password")); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return connection; } public static void releaseResource(Connection connection){ try { //释放DBMS对象资源-------断开连接 if(connection != null) connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } //测试一下 public static void main(String[] args) { System.out.println(getMysqlConn()); } }
(3)DRUD create增 read查 update改 delete删
另外放一个类里,在持久层中,dao里。(全是接口)
然后用实现类写具体方法
3.1 新增:
/** * @author: sunshine * @description: * @data: 2022/3/11 17:57 * @version: 0.1 * @since: jdk11 */ public interface UserinfoDao { //新增用户 /** * * @return 受影响的行记录数 */ int addUserinfo(); }
/** * @author: sunshine * @description: * @data: 2022/3/11 17:58 * @version: 0.1 * @since: jdk11 */ public class UserinfoImpl implements UserinfoDao { //实现新增用户的功能 @Override public int addUserinfo() { //对应的接口处方法类型也改成int //1.连接数据库 Connection connection = DBUtil.getMysqlConn(); //2.准备sql语句 String sql = "insert into tb_userinfo (name,gender,phone,age,balance,password,birthday) values('李四','男','1111',30,778766,'2828','2002-01-01')"; PreparedStatement statement = null; //PreparedStatement需要释放,但作用域小,需要放到外面 int result = 0; try { //3.将sql语句封装,并发送到DBMS中 statement = connection.prepareStatement(sql); //sql语句被封装到statement //4.执行sql语句 result = statement.executeUpdate(); //返回值,受影响的行记录数。 >=1成功 =0失败 } catch (SQLException throwables) { throwables.printStackTrace(); }finally { DBUtil.releaseResource(connection,statement); } return result; } }
注:这里工具类释放资源部分改动
public static void releaseResource(Connection connection, PreparedStatement ps){ //这两都得释放
try {
if(connection != null) connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
3.1新增优化,每来一个用户就改动一次,sql的语句不能写死。
public interface UserinfoDao { //新增用户 /** * * @return 受影响的行记录数 */ int addUserinfo(); //改进的新增 int addUserInfo1(Userinfo userinfo); }
@Setter @Getter @ToString public class Userinfo { private Integer id; private String name; private String gender; private String phone; private Integer age; private BigDecimal balance; private String password; private Date birthday; private Date createTime; private Date updateTime; private Date lastLoginTime; }
public class UserinfoImpl implements UserinfoDao { //实现新增用户的功能 @Override public int addUserinfo() { //对应的接口处方法类型也改成int //1.连接数据库 Connection connection = DBUtil.getMysqlConn(); //2.准备sql语句 String sql = "insert into tb_userinfo (name,gender,phone,age,balance,password,birthday) values('李四','男','1111',30,778766,'2828','2002-01-01')"; PreparedStatement statement = null; //PreparedStatement需要释放,但作用域小,需要放到外面 int result = 0; try { //3.将sql语句封装,并发送到DBMS中 statement = connection.prepareStatement(sql); //sql语句被封装到statement //4.执行sql语句 result = statement.executeUpdate(); //返回值,受影响的行记录数。 >=1成功 =0失败 } catch (SQLException throwables) { throwables.printStackTrace(); }finally { DBUtil.releaseResource(connection,statement); } return result; } //重写新增优化的方法(值是动态变化的) //可将name,gender等作为形参传入,但数量太多,不利于维护 //用映射关系:表里的一行记录就是类的一个对象 ,故创建用户类(实体类,放在bean包),并作为形参传入 @Override public int addUserInfo1(Userinfo userinfo) { //1.连接 Connection connection = DBUtil.getMysqlConn(); int result = 0; PreparedStatement ps = null; //2.用占位符 String sql = "insert into tb_userinfo (name,gender,phone,age,balance,password,birthday) values(?,?,?,?,?,?,?)"; try { //3.发送到数据库 ps = connection.prepareStatement(sql); //4.判断sql语句里是否有占位符,有的话赋值,占位符从1开始,没有索引 ps.setString(1,userinfo.getName()); //(第几个占位符,数据) ps.setString(2,userinfo.getGender()); ps.setString(3,userinfo.getPhone()); ps.setString(4,userinfo.getAge()); ps.setString(5,userinfo.getBalance()); ps.setString(6,userinfo.getPassword()); //需要将util.Date 转 sql.Date //法一:ps.setString(7,new Date(userinfo.getBirthday().getTime())); ps.setObject(7,userinfo.getBirthday()); //5.执行sql result = ps.executeUpdate(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { DBUtil.releaseResource(connection,ps); } return result; } }
/** * @author: sunshine * @description: 测试用户功能 * @data: 2022/3/11 18:36 * @version: 0.1 * @since: jdk11 */ public class UserinfoTest { //单元测试方法 public void a(){} 需要@Test @Test public void testAdd() { UserinfoDao userinfoDao = new UserinfoImpl(); int result = userinfoDao.addUserinfo(); System.out.println(result); //1,新增了一行记录 if(result>=1){ System.out.println("新增成功"); }else{ System.out.println("新增失败"); } } //优化新增 //使用@Test,不能实体Scanner(无法录入) //这里还用main做 public static void main(String[] args) { addTest(); } public static void addTest(){ //用户录入信息 Scanner input = new Scanner(System.in); Userinfo userinfo = new Userinfo(); System.out.println("请录入用户名"); userinfo.setName(input.next()); System.out.println("请录入性别"); userinfo.setGender(input.next()); System.out.println("请录入密码"); userinfo.setPassword(input.next()); System.out.println("请录入age"); userinfo.setAge(Integer.parseInt(input.next())); // System.out.println("请录入balance"); userinfo.setBalance(new BigDecimal(input.next())); System.out.println("请录入birthday"); userinfo.setBirthday(new Date()); UserinfoDao userinfoDao = new UserinfoImpl(); System.out.println(userinfoDao.addUserInfo1(userinfo)); } }
其它同理,代码如下:
工具类: scr.com.javasm.util.DBUtil
/**
* @author: sunshine
* @description: //将连接,释放功能封装到工具类
* @data: 2022/3/11 14:30
* @version: 0.1
* @since: jdk11
*/
public class DBUtil {
private DBUtil(){}
private static final Properties properties;
static{
properties = new Properties();
try {
properties.load(new FileInputStream("src\\jdbc.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getMysqlConn(){
Connection connection = null;
try {
Class.forName(properties.getProperty("jdbc.driver"));
connection = DriverManager.getConnection(
properties.getProperty("jdbc.url"),
properties.getProperty("jdbc.username"),
properties.getProperty("jdbc.password"));
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void releaseResource(Connection connection, PreparedStatement ps){ //这两都得释放
try {
if(connection != null) connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(getMysqlConn());
}
//重载该方法
public static void releaseResource(Connection connection, PreparedStatement ps, ResultSet rs){
try {
if(rs!=null) rs.close();
releaseResource(connection,ps);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
实体类---用户类 scr.com.javasm.bean.Userinfo
/**
* @author: sunshine
* @description:
* @data: 2022/3/11 19:50
* @version: 0.1
* @since: jdk11
*/
@Setter
@Getter
@ToString
public class Userinfo {
private Integer id;
private String name;
private String gender;
private String phone;
private Integer age;
private BigDecimal balance;
private String password;
private Date birthday;
private Date createTime;
private Date updateTime;
private Date lastLoginTime;
}
接口 scr.com.javasm.dao.UserinfoDao
/**
* @author: sunshine
* @description:
* @data: 2022/3/11 17:57
* @version: 0.1
* @since: jdk11
*/
public interface UserinfoDao {
//新增用户
/**
*
* @return 受影响的行记录数
*/
int addUserinfo();
//改进的新增
int addUserInfo1(Userinfo userinfo);
//根据id删除一个
int deleteUserInfoById(int uid);
//删多个
int deleteUserInfoByIds(List idList);
//查询单个 根据id查询一个用户信息 (映射关系:一行记录就是一个对象)
Userinfo findUserinfoById(int uid);
//修改单个 根据id修改用户 还是DML语句,故返int
//不清楚用户修改哪几个列,故默认全部都修改,直接用完整的用户对象
//该对象特殊,新增时装的全是新的数据。 这个是装一部分旧数据,装一部分新数据
int updateUserInfoById(Userinfo userinfo);
//查询所有用户
List findAllUserinfo();
}
接口实现类 scr.com.javasm.impl.UserinfoImpl
/**
* @author: sunshine
* @description:
* @data: 2022/3/11 17:58
* @version: 0.1
* @since: jdk11
*/
public class UserinfoImpl implements UserinfoDao {
//实现新增用户的功能
@Override
public int addUserinfo() { //对应的接口处方法类型也改成int
//1.连接数据库
Connection connection = DBUtil.getMysqlConn();
//2.准备sql语句
String sql = "insert into tb_userinfo (name,gender,phone,age,balance,password,birthday) values('李四','男','1111',30,778766,'2828','2002-01-01')";
PreparedStatement statement = null; //PreparedStatement需要释放,但作用域小,需要放到外面
int result = 0;
try {
//3.将sql语句封装,并发送到DBMS中
statement = connection.prepareStatement(sql); //sql语句被封装到statement
//4.执行sql语句
result = statement.executeUpdate(); //返回值,受影响的行记录数。 >=1成功 =0失败
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.releaseResource(connection,statement);
}
return result;
}
//重写新增优化的方法(值是动态变化的)
//可将name,gender等作为形参传入,但数量太多,不利于维护
//用映射关系:表里的一行记录就是类的一个对象 ,故创建用户类(实体类,放在bean包),并作为形参传入
@Override
public int addUserInfo1(Userinfo userinfo) {
//1.连接
Connection connection = DBUtil.getMysqlConn();
int result = 0;
PreparedStatement ps = null;
//2.用占位符
String sql = "insert into tb_userinfo (name,gender,phone,age,balance,password,birthday) values(?,?,?,?,?,?,?)";
try {
//3.发送到数据库
ps = connection.prepareStatement(sql);
//4.判断sql语句里是否有占位符,有的话赋值,占位符从1开始,没有索引
ps.setString(1,userinfo.getName()); //(第几个占位符,数据)
ps.setString(2,userinfo.getGender());
ps.setString(3,userinfo.getPhone());
ps.setString(4, String.valueOf(userinfo.getAge()));
ps.setString(5, String.valueOf(userinfo.getBalance()));
ps.setString(6,userinfo.getPassword());
//需要将util.Date 转 sql.Date
//法一:ps.setString(7,new Date(userinfo.getBirthday().getTime()));
ps.setObject(7,userinfo.getBirthday());
//5.执行sql
result = ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.releaseResource(connection,ps);
}
return result;
}
@Override
public int deleteUserInfoById(int uid) {
Connection connection = DBUtil.getMysqlConn();
PreparedStatement ps = null;
int result = 0;
String sql ="delete from tb_userinfo where id=?";
try {
ps = connection.prepareStatement(sql);
ps.setObject(1,uid);
result = ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.releaseResource(connection,ps);
}
return result;
}
@Override
public int deleteUserInfoByIds(List idList) {
Connection connection = DBUtil.getMysqlConn();
//不知有几个id,动态拼接占位符
StringBuilder builder = new StringBuilder("delete from tb_userinfo where id in (");
int size = idList.size();
for (int i = 1; i <= size; i++) {
builder.append("?");
if(i==size){
builder.append(")");
break;
}
builder.append(",");
}
PreparedStatement ps = null;
int result = 0;
try {
//发送
ps = connection.prepareStatement(builder.toString());
//赋值
for (int i = 1; i <= size; i++) {
ps.setObject(i,idList.get(i-1));
}
//执行
result = ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.releaseResource(connection,ps);
}
return result;
}
@Override
public Userinfo findUserinfoById(int uid) {
Connection connection = DBUtil.getMysqlConn();
String sql = "SELECT id,name, gender, phone, age, balance, password, birthday, create_time, update_time, last_long_time FROM tb_userinfo WHERE id = ?";
Userinfo userinfo = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = connection.prepareStatement(sql);
ps.setInt(1,uid);
//执行sql,executeUpdate()只能执行DML语句,select是DQL语句
rs = ps.executeQuery();
//String getString(int columnIndex) 获得指定列的数据 用它的情况:查询结果有且只有1列的时候
// String getString(String columnLabel) 根据列名获得列对应的数据
if(rs.next()){ //判断光标或指针之后是否有更多记录需要被遍历
userinfo = new Userinfo();
userinfo.setId(uid);
userinfo.setName(rs.getString("name"));
userinfo.setPassword(rs.getString("password"));
userinfo.setGender(rs.getString("gender"));
userinfo.setBalance(rs.getBigDecimal("balance"));
userinfo.setBirthday(rs.getDate("birthday"));
userinfo.setAge(rs.getInt("age"));
//其他不拿值的都为null
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.releaseResource(connection,ps,rs); //又多了一个资源要释放 需要在工具类里重载
}
return userinfo;
}
@Override
public int updateUserInfoById(Userinfo userinfo) {
Connection connection = DBUtil.getMysqlConn();
String sql ="UPDATE tb_userinfo SET name=?, gender=?, phone=?, age=?, balance=?, password=?, birthday=? WHERE id =?";
PreparedStatement ps = null;
int result = 0;
try {
ps = connection.prepareStatement(sql);
ps = connection.prepareStatement(sql);
ps.setString(1, userinfo.getName());
ps.setString(2, userinfo.getGender());
ps.setString(3, userinfo.getPhone());
ps.setInt(4, userinfo.getAge());
ps.setBigDecimal(5, userinfo.getBalance());
ps.setString(6, userinfo.getPassword());
ps.setObject(7, userinfo.getBirthday());
ps.setObject(8, userinfo.getId());
result = ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.releaseResource(connection,ps);
}
return result;
}
@Override
public List findAllUserinfo() {
Connection connection = DBUtil.getMysqlConn();
String sql ="SELECT * FROM tb_userinfo";
List userinfoList = new ArrayList<>(10);
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = connection.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
userinfoList.add(userinfoInstance(rs));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.releaseResource(connection,ps,rs);
}
return userinfoList;
}
private Userinfo userinfoInstance(ResultSet rs) throws SQLException {
Userinfo userinfo = new Userinfo();
userinfo.setId(rs.getInt("id"));
userinfo.setName(rs.getString("name"));
userinfo.setPassword(rs.getString("password"));
userinfo.setGender(rs.getString("gender"));
userinfo.setBalance(rs.getBigDecimal("balance"));
userinfo.setBirthday(rs.getDate("birthday"));
userinfo.setAge(rs.getInt("age"));
return userinfo;
}
}
测试类 scr.test.com.javasm.test.UserinfoTest
/**
* @author: sunshine
* @description: 测试用户功能
* @data: 2022/3/11 18:36
* @version: 0.1
* @since: jdk11
*/
public class UserinfoTest {
//单元测试方法 public void a(){} 需要@Test
@Test
public void testAdd() {
UserinfoDao userinfoDao = new UserinfoImpl();
int result = userinfoDao.addUserinfo();
System.out.println(result); //1,新增了一行记录
if(result>=1){
System.out.println("新增成功");
}else{
System.out.println("新增失败");
}
}
//优化新增
//使用@Test,不能实体Scanner(无法录入)
//这里还用main做
public static void main(String[] args) {
//addTest();
//updateTest();
findAllUserinfoTest();
}
public static void addTest(){
//用户录入信息
Scanner input = new Scanner(System.in);
Userinfo userinfo = new Userinfo();
System.out.println("请录入用户名");
userinfo.setName(input.next());
System.out.println("请录入性别");
userinfo.setGender(input.next());
System.out.println("请录入密码");
userinfo.setPassword(input.next());
System.out.println("请录入age");
userinfo.setAge(Integer.parseInt(input.next())); //
System.out.println("请录入balance");
userinfo.setBalance(new BigDecimal(input.next()));
System.out.println("请录入birthday");
userinfo.setBirthday(new Date());
UserinfoDao userinfoDao = new UserinfoImpl();
System.out.println(userinfoDao.addUserInfo1(userinfo));
}
@Test
public void deleteUserInfoByIdTest() {
UserinfoDao userinfoDao = new UserinfoImpl();
System.out.println(userinfoDao.deleteUserInfoById(9));
//删多个 弊端:浪费资源,每循环一次就打开连接,关闭连接一次
/* List idList = List.of(2,7);
for(Integer id:idList){
System.out.println(userinfoDao.deleteUserInfoById(id));
}*/
}
@Test
public void deleteUserInfoByIdsTest() {
UserinfoDao userinfoDao = new UserinfoImpl();
List idList = List.of(11,12);
System.out.println(userinfoDao.deleteUserInfoByIds(idList));
}
@Test
public void findOneTest(){
UserinfoDao userinfoDao = new UserinfoImpl();
System.out.println(userinfoDao.findUserinfoById(1));
}
private static void updateTest() { //先查再改
UserinfoDao userinfoDao = new UserinfoImpl();
Scanner input = new Scanner(System.in);
System.out.println("请录入要修改的id");
int id = input.nextInt();
Userinfo userinfo = userinfoDao.findUserinfoById(id); //旧值全在这里
System.out.println("要修改的用户信息如下:"+userinfo);
System.out.println("请录入要修改的列:1.name 2.phone 3.age 4.password");
String choiceStr = input.nextLine(); //一般输入1,2 1,2,3这样的形式
String[] array = choiceStr.split(","); //用,分割
for (String s : array) {
int choice = Integer.parseInt(s);
switch (choice) {
case 1:
System.out.println("请录入新的name:");
String newName = input.next();
userinfo.setName(newName);
break;
case 2:
System.out.println("请录入新的phone:");
String newPhone = input.next();
userinfo.setPhone(newPhone);
break;
case 3:
System.out.println("请录入新的age:");
int newAge = input.nextInt();
userinfo.setAge(newAge);
break;
case 4:
System.out.println("请录入新的password:");
String newPassword = input.next();
userinfo.setPassword(newPassword);
break;
}
}
System.out.println(userinfoDao.updateUserInfoById(userinfo)); //传入修改后的userinfo
}
public static void findAllUserinfoTest() {
UserinfoDao userinfoDao = new UserinfoImpl();
userinfoDao.findAllUserinfo().forEach(System.out::println);
}
}