gpt4 book ai didi

java - 创建唯一的 listing_no (Java/PostgreSQL)

转载 作者:行者123 更新时间:2023-11-29 13:15:33 25 4
gpt4 key购买 nike

我正在研究菜单功能中的一个选项,该功能将待售汽车发布到数据库中。该选项要求用户输入年份、品牌、条件和价格,然后将其插入到数据库中的表 car_sale 中。但是,在此选项期间还必须生成唯一的 listing_no。我无法定义我的表以唯一生成 10 位数字的选项,但我必须对程序进行编码以插入唯一生成的 listing_no。您会在下面找到我尝试执行此操作的代码,但是该代码仅适用于 Oracle,但我无法使用 Oracle。我只会 PostGreSQL 和 Java。因此,我的问题出现了,因为我正在使用的函数和关系不能在 PostGre 中使用。

生成商品编号的代码:

 public int generateListingNo() throws SQLException
{
int listingSeq = 0;
Statement select = connection.createStatement();
result = select.executeQuery("select (to_char(sysdate,'yyyymmdd')||AUDIT_SEQ.NEXTVAL)valnext from dual");;
if(result.next())
{
listingSeq = result.getInt(1);
}

int seq = listingSeq;

return seq;
}

选项函数中的代码插入从generateListingNo()生成的listing_no

public void option() throws SQLException
{
int listing_no = generateListingNo();
// insert information into books_for_sale table
sql_insert = "INSERT INTO car_sale VALUES(" + listing_no +", "
+ "'" + year + "'" + ", " +
"'" + make + "'" +", " +
"'" + condition + "'" + ", "
+ price + ")";

我遇到的错误:

    Exception in thread "main" org.postgresql.util.PSQLException: ERROR: relation "dual" does not exist
Position: 69 at
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:217)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:421)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:318)
at org.postgresql.jdbc.PgStatement.executeQuery(PgStatement.java:281)

创建 car_sale 表

create table car_sale(
listing_no int not null,
year varchar not null,
make varchar not null,
condition varchar not null,
price decimal(12,2) not null,
primary key (listing_no),

最佳答案

更改您对 generateListingNo 的查询,如下所示:

select   q from (select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ') )q )sq

select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ')) as newseqval 

或者在你的代码上:

public int generateListingNo() throws SQLException
{
int listingSeq = 0;
Statement select = connection.createStatement();
result = select.executeQuery("select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ')) as newseqval");;
if(result.next())
{
listingSeq = result.getInt(1);
}

int seq = listingSeq;

return seq;
}

因为你没有序列:

使用以下查询创建序列:

CREATE SEQUENCE public."AUDIT_SEQ"
INCREMENT 1
START 1
MINVALUE 1
MAXVALUE 9223372036854775807
CACHE 1;

或使用 UUID:

public String generateListingNo() throws SQLException
{
return UUID.randomUUID().toString();
}

您的表结构需要更改:

create table car_sale(
listing_no varchar not null,
year varchar not null,
make varchar not null,
condition varchar not null,
price decimal(12,2) not null,
primary key (listing_no),

关于java - 创建唯一的 listing_no (Java/PostgreSQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49588930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com