gpt4 book ai didi

java - 使用 JDBC 将值插入到 postgresql

转载 作者:可可西里 更新时间:2023-11-01 08:09:28 25 4
gpt4 key购买 nike

<分区>

我想使用 java 创建类似任务管理器的东西。我决定使用 PostgreSQL 来保存我的任务。此时,我想将创建的任务保存到 PostgreSQL,为此我有以下代码:

package TaskMgr;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Task {

private String title;
private String description;
private LocalDate dateFormat;


public Task(String title, String description, String date) {
this.title = title;
this.description = description;
this.dateFormat = setDate(date);
}


public LocalDate setDate(String inputDate) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("yyyy-MM-d")
.toFormatter(Locale.ENGLISH);
formatter = formatter.withLocale(Locale.ENGLISH);
LocalDate outputDate = LocalDate.parse(inputDate, formatter);
return outputDate;

}

public String getTitle() {
return title;
}

public String getDescription() {
return description;
}


public LocalDate getDateFormat() {
return dateFormat;
}

public static void main(String[] args) {

}


}

我的数据库代码:(已经创建了带有表任务的数据库,其中包含字段:文本类型的标题、文本类型的描述和日期类型的日期)。这是数据库类的代码:

package TaskMgr;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.Month;

public class Database {

private final String url = "jdbc:postgresql://localhost/tasksdb";
private final String user = "postgres";
private final String password = "31415926";

public Connection connect() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the PostgreSQL server successfully.");

} catch (SQLException e) {
System.out.println(e.getMessage());
}

return conn;
}

public void createItem(int idCur, String title, String description, LocalDate date) {
try {
Statement stmnt = null;
stmnt = connect().createStatement();
String sql = "INSERT INTO TASKS (ID,TITLE,DESCRIPTION,DATE) "
+ "VALUES " + "(" + idCur + ", " + title + ", " + description + ", " + date + ")";
stmnt.executeUpdate(sql);

} catch (SQLException e) {
System.out.println(e.getMessage());
}

}

public static void main(String[] args) {
Database database = new Database();
database.connect();
Task task = new Task("'Test2'", "'Test2 description'", "1998-01-07");
database.createItem(2, task.getTitle(), task.getDescription(), task.getDateFormat());

}

但 Intellij 抛出以下错误:

ERROR: column "date" is of type date but expression is of type integer
TIP: You will need to rewrite or cast the expression.

我试图用谷歌搜索这个错误,但没有任何帮助。我应该如何处理我的约会对象?

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