【JAVA】Mysql varchar自增ID

import utils.DBHelper;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import java.text.SimpleDateFormat;

import java.util.Date;


public class CreateID {
    static DBHelper dbHelper = new DBHelper();
    Connection conn = dbHelper.getConn(); // 获取连接
    Statement stmt = null;

    /**
    * 
    * 
    * @param head
    *            头部编号
    * @param col
    *            字段名称
    * @param tableName
    *            数据表名称
    * @return
    * @throws Exception
    */
    public String createID(String head, String col, String tableName)
        throws Exception {
        stmt = conn.createStatement();

        // 获取编号最大值
        String sql = "select " + col + " from " + tableName + " order by " +
            col + " desc limit 0,1";
        ResultSet rs = stmt.executeQuery(sql);

        String value = null; // 课程编号值
        ResultSetMetaData metaData = rs.getMetaData();

        if (rs.next()) {
            // 此方法返回列的别名。如果列别名不可用,此方法将返回列名称。
            String columnName = metaData.getColumnLabel(1);
            // 获取到最大的编号值
            value = rs.getString(columnName);
        }

        if (value == null) {
            // 如果编号是空,则新增为"KC0001"
            value = head + "0001";
        } else {
            // 取出后4位流水号
            value = value.substring(2, 6);

            int num = Integer.parseInt(value) + 1; // 实现编号自增
            int length = Integer.toString(num).length();
            String zero = "";

            // 将剩余位数补全为0
            for (int i = 0; i < (4 - length); i++) {
                zero += "0";
            }

            value = head + zero + num; // 返回流水号的数值
        }

        dbHelper.closeConn();

        return value;
    }

    /**
    * 
    * @param head
    * @param col
    * @param tableName
    * @return
    * @throws Exception
    */
    public String createOrderID(String head, String col, String tableName)
        throws Exception {
        stmt = conn.createStatement();

        String sql = "select " + col + " from " + tableName + " order by " +
            col + " desc limit 0,1";
        ResultSet rs = stmt.executeQuery(sql);

        String value = null;
        String dateNow = new SimpleDateFormat("yyyyMM").format(new Date());

        ResultSetMetaData metaData = rs.getMetaData();

        if (rs.next()) {
            metaData.getColumnCount();

            String columnName = metaData.getColumnLabel(1);

            value = rs.getString(columnName);
        }

        if (value == null) {
            value = head + dateNow + "0001";
        } else {
            String date = value.substring(3, 9);

            if (date.equals(dateNow)) {
                value = value.substring(9, 13);

                int num = Integer.parseInt(value) + 1;
                int length = Integer.toString(num).length();
                String zero = "";

                for (int i = 0; i < (4 - length); i++) {
                    zero += "0";
                }

                value = head + date + zero + num;
            } else {
                value = head + dateNow + "0001";
            }
        }

        dbHelper.closeConn();

        return value;
    }

    public String createEmpId() throws Exception {
        return createID("XD", "employeeid", "employeebasicinfo");
    }

    public String createPetId() throws Exception {
        return createOrderID("Pet", "petid", "petinfo");
    }

    public static void main(String[] args) {
        try {
            System.out.println(new CreateID().createPetId());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要设置Java中的主键自增,你需要在数据库表的主键字段上使用自增长属性,并在Java代码中做一些相应的配置。下面是一个示例: 1. 在数据库中设置自增主键 假设你的数据库表为`user`,主键字段名为`id`,你可以使用数据库自增长属性来设置主键自增。具体的语法可能会因数据库类型而有所差异,以下是MySQL和Oracle数据库的示例: - MySQL: ```sql CREATE TABLE user ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), age INT ); ``` - Oracle: ```sql CREATE TABLE user ( id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY PRIMARY KEY, name VARCHAR2(50), age NUMBER ); ``` 2. 在Java代码中配置主键自增Java的实体类或数据访问层中,你需要进行一些配置才能实现主键自增。以下是一些示例: - 使用JPA注解(适用于Spring框架): ```java import javax.persistence.*; @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; // 其他属性和方法 } ``` - 使用MyBatis注解(适用于MyBatis框架): ```java public interface UserMapper { @Insert("INSERT INTO user (name, age) VALUES (#{name}, #{age})") @Options(useGeneratedKeys = true, keyProperty = "id") void insertUser(User user); // 其他方法 } ``` 在上述示例中,使用了JPA注解的`@GeneratedValue(strategy = GenerationType.IDENTITY)`和MyBatis注解的`@Options(useGeneratedKeys = true, keyProperty = "id")`来配置主键自增。这将告诉数据库在插入数据时生成自增的主键值,并将其赋值给Java对象的`id`属性。 请根据你使用的框架和数据库类型进行相应的配置。希望以上信息对你有所帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rorschach01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值