Java连接MySQL数据库进行增删改查demo【入门级】

总体步骤 

  1. jdbc静态代码块读取配置文件信息获得driverurlusernamepassword,并驱动Driver类(需要导入对应的jar包),其中Driver类用来获得Connection
  2. jdbc就可以使用getConnection方法获得Connection(与MySQL连接的代理)。
  3. 通过Connection配合PreparedStatement 我们就可以执行任意的sql语句了,最后记得使用release方法释放资源。
  4. 最终我们只关心sql语句的描述即可。


开始实践

导入jar包

MySQL 5MySQL 8不同(根据自己MySQL版本去百度下载对应的jar包),这个jar包帮我们处理连接的细节,我们只要配置上一些基础信息即可。


配置文件 

命名方式  (自定义名称).properties ,需要提供driverurlusernamepassword的信息。

url格式:"jdbc:mysql://localhost:3306/"+数据库名+"?useSSL=false&&serverTimezone=UTC"

username:数据库账号。

password:数据库密码。

配置文件样例(这driver是8.0的,5.0的只需把cj去掉即可):

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/goods_manage?useSSL=false&&serverTimezone=UTC
username=root
password=1234

JDBC工具类 

主要用来获得Connection

package com.han.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

   //静态代码块只会执行一次(第一次使用Jdbc的时候)
    static {
        //获得配置文件的输入流(配置文件流>>程序内存) 配置文件路径在src一级子目录
        InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
        //配置类
        Properties properties = new Properties();
        try {
            properties.load(in);//读取流
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            Class.forName(driver);//驱动mysql8.0的jar包
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,username,password);
    }
    //关闭连接,节省资源
    public static void release(Connection con, Statement st, ResultSet rs){
        try{
            if(con != null) con.close();
            if(rs != null) rs.close();
            if(st != null) st.close();
        }catch (Exception e){
            System.out.println(e);
        }
    }

}

这样就可以开始快乐的CRUD了。(CRUD:增删改查)


Dao层

GoodsService接口

package com.han.service;

import com.han.pojo.Goods;
import java.sql.SQLException;

public interface GoodsService {
    void insert(Goods goods) throws SQLException;
    void delete(Integer id) throws SQLException;
     void update(Integer id,String field,T value) throws SQLException;
    void select(Integer id) throws SQLException;
}

GoodsServiceImpl类实现了GoodsService接口

其实增删改查都差不多,先通Jdbc获得connection,再用con加载sql语句后放入ps中,ps放置占位符对应的参数后执行ps的方法( 修改表的是ps.execute(),获得表记录的是ps.executeQuery() ),执行结束后调用release释放资源。

package com.han.service;

import com.han.Utils.JdbcUtil;
import com.han.pojo.Goods;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GoodsServiceImpl implements GoodsService{
    private static final int ALL = -1;

    @Override
    public void insert(Goods goods) throws SQLException {
        Connection con = JdbcUtil.getConnection();
        String sql = "insert into goods(goods_name,goods_type,goods_price,goods_num) values(?,?,?,?)";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1,goods.getGoodsName());
        ps.setString(2,goods.getGoodsType());
        ps.setInt(3,goods.getGoodsPrice());
        ps.setInt(4,goods.getGoodsNum());
        ps.execute();
        JdbcUtil.release(con,ps,null);
    }

    @Override
    public void delete(Integer id) throws SQLException {
        String sql = "delete from goods where id=?";
        Connection con = JdbcUtil.getConnection();
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setInt(1,id);
        ps.execute();
        JdbcUtil.release(con,ps,null);
    }

    @Override
    public  void update(Integer id,String field,T value) throws SQLException {
        String sql = "update goods set "+field+"=? where id=?";
        Connection con = JdbcUtil.getConnection();
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1,value);
        ps.setInt(2,id);
        ps.execute();
        JdbcUtil.release(con,ps,null);
    }

    @Override
    public void select(Integer id) throws SQLException {
        String sql;
        Connection con = JdbcUtil.getConnection();
        PreparedStatement ps = null;
        if(id != ALL){
            sql = "select * from goods where id=?";
            ps = con.prepareStatement(sql);
            ps.setInt(1,id);
        }else {
            sql = "select * from goods";
            ps = con.prepareStatement(sql);
        }
        ResultSet rs = ps.executeQuery();
        System.out.println("**********************************************************************");
        while(rs.next()){
            Goods goods = new Goods();
            goods.setId(rs.getInt("id"));
            goods.setGoodsName(rs.getString("goods_name"));
            goods.setGoodsType(rs.getString("goods_type"));
            goods.setGoodsPrice(rs.getInt("goods_price"));
            goods.setGoodsNum(rs.getInt("goods_num"));
            System.out.println(goods.getId()+" "+goods.getGoodsName()+" "+goods.getGoodsType()+" "+goods.getGoodsPrice()+" "+goods.getGoodsNum());
        }
        System.out.println("**********************************************************************");
        JdbcUtil.release(con,ps,rs);
    }
}


POJO(实体类)

Goods类

package com.han.pojo;

public class Goods {
    private int id;
    private String goodsName;
    private String goodsType;
    private int goodsPrice;
    private int goodsNum;

    public Goods() {
    }

    public Goods(String goodsName, String goodsType, int goodsPrice, int goodsNum) {
        this.goodsName = goodsName;
        this.goodsType = goodsType;
        this.goodsPrice = goodsPrice;
        this.goodsNum = goodsNum;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getGoodsName() {
        return goodsName;
    }

    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }

    public String getGoodsType() {
        return goodsType;
    }

    public void setGoodsType(String goodsType) {
        this.goodsType = goodsType;
    }

    public int getGoodsPrice() {
        return goodsPrice;
    }

    public void setGoodsPrice(int goodsPrice) {
        this.goodsPrice = goodsPrice;
    }

    public int getGoodsNum() {
        return goodsNum;
    }

    public void setGoodsNum(int goodsNum) {
        this.goodsNum = goodsNum;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "id=" + id +
                ", goodsName='" + goodsName + '\'' +
                ", goodsType='" + goodsType + '\'' +
                ", goodsPrice=" + goodsPrice +
                ", goodsNum=" + goodsNum +
                '}';
    }
}


测试

package com.han.Test;

import com.han.pojo.Goods;
import com.han.service.GoodsService;
import com.han.service.GoodsServiceImpl;

import java.sql.SQLException;

public class MyTest {
    private static final int ALL = -1;
    public static void main(String[] args) throws SQLException {

        //增删改查工作交给它完成
        GoodsService goodsService = new GoodsServiceImpl();

        Goods goods = new Goods("柠檬", "水果", 1, 30);

        //往goods表中插入一条数据
        goodsService.insert(goods);

        //更改goods表id为5的商品名称
        goodsService.update(5,"goods_name","emo");

        //更改goods表id为5的价格
        goodsService.update(5,"goods_price",1);

        //删出goods表id为3的记录
        goodsService.delete(3);

        //获得表中所有记录
        goodsService.select(ALL);
    }
}


 项目结构:

Java连接MySQL数据库进行增删改查demo【入门级】_第1张图片

goods表结构

Java连接MySQL数据库进行增删改查demo【入门级】_第2张图片

Java连接MySQL数据库进行增删改查demo【入门级】_第3张图片

你可能感兴趣的:(Java,mysql,java,数据库)