我想在 PostgreSQL 数据库中插入一条记录。它的大部分字段是字符串,但也有 java.sql.date 和 BIGINT。我怎样才能做到这一点?我的代码似乎不起作用。
public Record(RecordFields data)
{
CreateNewRecord(data);
}
private void CreateNewRecord(RecordFields recordFields)
{
try
{
String addRecord = "INSERT INTO " + GlobalFields.TABLE + " VALUES (? , ? , ? , ? , ? , ? , ? , ? , ?);";
Connection conn = DataBase.Connect();
PreparedStatement query = conn.prepareStatement(addRecord);
query.setLong(1, recordFieldsID);
query.setString(2, recordFields.surname);
query.setString(3, recordFields.name);
query.setString(4, recordFields.sex);
DateTime date = recordFields.bornDate.toDateTime();
query.setTimestamp(5, new Timestamp(date.getMillis()));
query.setString(6, recordFields.adress);
query.setString(7, recordFields.contact);
query.setString(8, recordFields.insurance);
query.setString(9, recordFields.commentary);
query.executeUpdate(addRecord);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
表生成器:
public static void CreateTable()
{
try
{
Connection conn = DataBase.Connect();
try
{
Statement stat = conn.createStatement();
String createTable = "CREATE TABLE " + GlobalFields.TABLE
+ "(id BIGINT PRIMARY KEY,"
+ "surname TEXT,"
+ "name TEXT,"
+ "sex CHAR(1),"
+ "bornDate DATE,"
+ "adress TEXT,"
+ "contact TEXT,"
+ "insurance TEXT,"
+ "commentary TEXT);";
stat.executeUpdate(createTable);
}
finally
{
conn.close();
}
}
catch(SQLException e)
{
e.printStackTrace();
}
}
公共类 RecordFields { 公共 RecordFields() { }
public long id;
public String surname;
public String name;
public String sex;
public MutableDateTime bornDate;
public String adress;
public String contact;
public String insurance;
public String commentary;
}