关闭

解决数据库非主键自增长的方法

标签: Java数据库非主键
74人阅读 评论(0) 收藏 举报
1:编写获得下一个编号的方法
	//获取编号的next值
	private static String nextId = "";
	public static String getNextId(String curId, String pattern) {

		String curNum = curId.substring(curId.lastIndexOf("_") + 1);
		Integer nextNum = Integer.parseInt(curNum) + 1;
		DecimalFormat df = new DecimalFormat(pattern);
		nextId = curId.substring(0, curId.lastIndexOf("_") + 1)
				+ df.format(nextNum);
		return nextId;
	}:
2:操作数据库
<span style="white-space:pre"><span style="white-space:pre">	</span>//执行保存或更新动作	</span>
<span style="white-space:pre">	</span>public void saveOrUpdate(Product product) {
<span style="white-space:pre">		</span>String sql = "";
<span style="white-space:pre">		</span>try {
<span style="white-space:pre">			</span>DataSource ds = DataSourceUtil.getDataSource();
<span style="white-space:pre">			</span>conn = ds.getConnection();
<span style="white-space:pre">			</span>sql = "SELECT productId FROM `product` ORDER BY productId DESC LIMIT 1";<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>ps = conn.prepareStatement(sql);
<span style="white-space:pre">			</span>rs = ps.executeQuery();
<span style="white-space:pre">			</span>String newUserId = "";
<span style="white-space:pre">			</span>if(rs.next()){
<span style="white-space:pre">				</span>newUserId = StringUtil.getNextId(rs.getString("productId"),"000");
<span style="white-space:pre">			</span>}else{
<span style="white-space:pre">				</span>newUserId = "product_001";
<span style="white-space:pre">			</span>}
<span style="white-space:pre">			</span>sql="insert into product values(null, ?, ?, ?, ?)";
<span style="white-space:pre">			</span>ps = conn.prepareStatement(sql);
<span style="white-space:pre">			</span>ps.setString(1, newUserId);
<span style="white-space:pre">			</span>ps.setString(2, product.getName());
<span style="white-space:pre">			</span>ps.setString(3, product.getStatus());
<span style="white-space:pre">			</span>ps.setString(4, product.getRemarks());
<span style="white-space:pre">			</span>ps.executeUpdate();
<span style="white-space:pre">		</span>} catch (Exception e) {
<span style="white-space:pre">			</span>e.printStackTrace();
<span style="white-space:pre">		</span>} finally {
<span style="white-space:pre">			</span>try {
<span style="white-space:pre">			</span>ps.close();
<span style="white-space:pre">			</span>conn.close();
<span style="white-space:pre">			</span>} catch (SQLException e) {
<span style="white-space:pre">			</span>e.printStackTrace();
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:723次
    • 积分:19
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章存档