当前位置:Gxlcms > 数据库问题 > JDBC系列:(6)使用PreparedStatement获取自增长值

JDBC系列:(6)使用PreparedStatement获取自增长值

时间:2021-07-01 10:21:17 帮助过:29人阅读


T_Persons表是一个表示“人”的表。

T_Dogs表是一个表示“狗狗”的表,在T_Dogs表中有一个外键MasterId指向T_Persons表的主键Id。


package com.rk.db.f_auto_increment;

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

import com.rk.db.utils.JDBCUtil;

public class Demo01
{
	public static void main(String[] args)
	{
		Connection conn = null;
		PreparedStatement pstmt1 = null;
		PreparedStatement pstmt2 = null;
		ResultSet rs = null;
		try
		{
			String sql1 = "insert into T_Persons(UserName,Pwd) values(?,?)";
			String sql2 = "insert into T_Dogs(dName,MasterId) values(?,?)";
			//获得连接
			conn = JDBCUtil.getConnection();
			
			// 1、需要指定返回自增长标记
			pstmt1 = conn.prepareStatement(sql1,Statement.RETURN_GENERATED_KEYS);
			pstmt1.setString(1, "小红");
			pstmt1.setString(2, "password");			
			pstmt1.executeUpdate();
			
			// 2、得到返回的自增长字段
			int masterId = -1;
			rs = pstmt1.getGeneratedKeys();			
			if(rs.next())
			{
				masterId = rs.getInt(1);
			}
			
			// 3、使用返回的自增长字段
			pstmt2 = conn.prepareStatement(sql2);
			pstmt2.setString(1, "旺财");
			pstmt2.setInt(2, masterId);
			pstmt2.executeUpdate();
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		finally
		{
			JDBCUtil.closeQuietly(pstmt1);
			JDBCUtil.closeQuietly(pstmt2);
			JDBCUtil.closeQuietly(conn);
		}
	}
}




JDBC系列:(6)使用PreparedStatement获取自增长值

标签:generatedkeys   jdbc   preparedstatement   

人气教程排行