jdbc获取自增主键ID
所属分类 java
浏览量 622
Statement.RETURN_GENERATED_KEYS
PreparedStatement preparedStatement = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
create table person(id int primary key auto_increment,name varchar(16))
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class AutoIncrementIdGetTest {
public static void main(String[] args) throws Exception {
Connection conn = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
// create table person(id int primary key auto_increment,name varchar(16))
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
String sql = "insert into person(name) values(?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, "tiger");
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
rs.next();
int id = rs.getInt(1);
System.out.println("id=" + id);
} finally {
if (conn != null) {
conn.close();
}
}
}
}
上一篇
下一篇
时序数据库技术点
scala Option(null) 和 Some(null) 的区别
scala Option 小结
pf4j简介及例子运行说明
pf4j 例子应用 类加载机制验证
Play2.6.x开始使用Akka HTTP作为默认服务后端