How to get mysql primary key id just inserted

The first method: inserting a first data

INSERT into ecom_order(MemberID,GoodsTotalCounts,GoodsTotalFee,SAID,OrderTime,Status,AddTime,Remark) VALUES(1016,5,360,8,now(),1,now(),'无')

Use the following query

SELECT LAST_INSERT_ID(); 即可获取

The second method:

PreparedStatement pstmt = conn.prepareStatement (sql, Statement.RETURN_GENERATED_KEYS); // Get automatically increase the id

Complete wording (java language):

	public int returnID(String sql) throws Exception {
		// 检测数据库连接,若没有开启,则本方法自动启开,并在方法末尾自动关闭
		boolean openConnHere = false;
		if (conn == null) {
			this.openConnection();
			openConnHere = true;
		}

		// 准备执行SQL语句
		java.sql.Statement stmt = (java.sql.Statement) conn.createStatement();
		
		// 执行Sql语句并返回本条信息的主键ID
		stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
		
		int rValue = -1;

		// 获取新插入记录id
		ResultSet results = stmt.getGeneratedKeys();
		if (results.next()) {
			rValue = results.getInt(1);
		}

		// 若自动关闭连接开启,本方法结束的时候关闭连接
		if (openConnHere) {
			this.closeConnection();
		}

		return rValue;
}

 

Guess you like

Origin blog.csdn.net/qq_39404258/article/details/90901545