跟汤老师学Java笔记:怎么返回插入自动生成的主键id

跟汤老师学Java笔记:怎么返回插入自动生成的主键id

完成:第一遍

1.怎么返回插入自动生成的主键id?

String sql=new StringBuffer()
.append(" insert into “)
.append(” t_user “)
.append(” (username,password,age) “)
.append(” values “)
.append(” (‘lisi’,‘54321’,18) ")
.toString();

conn=JdbcUtil.getConnection();
传入常量值RETURN_GENERATED_KEYS,表示返回生成的主键
ps=conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);

ps.executeUpdate();
获取存储主键的结果集
rs=ps.getGeneratedKeys();
while(rs.next()){ //可能是复合主键
System.out.println(rs.getInt(1));
}

JdbcUtil 类:

package sms;

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

/**
 * JDBC工具类
 */
public class JdbcUtil {
	/**
	 * 获取数据库连接
	 */
	public static Connection getConnection() {
		String driverClassName = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true";
		String username = "root";
		String password = "123456";

		Connection conn = null;
		try {
			Class.forName(driverClassName);
			conn = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭资源
	 */
	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(Connection conn, Statement stmt) {
		close(conn, stmt, null);
	}
}

TestReturnID 类:

package sms;

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

public class TestReturnID {
	public static void main(String[] args) {
		
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		
		String sql=new StringBuffer()
			.append("   insert into ")
			.append(" 	t_user ")
			.append(" 	(username,password,age) ")
			.append("    values ")
			.append(" 	('lisi','54321',18) ")
			.toString();
			
		try {
			conn=JdbcUtil.getConnection();
			// 传入常量值RETURN_GENERATED_KEYS,表示返回生成的主键
			ps=conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
			ps.executeUpdate();
			
			//获取存储主键的结果集
			rs=ps.getGeneratedKeys();
			while(rs.next()){ //可能是复合主键
				System.out.println(rs.getInt(1));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JdbcUtil.close(conn, ps);
		}
	}
}

你可能感兴趣的:(Java之JDBC数据库连接,jdbc)