gpt4 book ai didi

java - 将 LinkedList 值插入数据库

转载 作者:行者123 更新时间:2023-12-01 16:33:38 54 4
gpt4 key购买 nike

这是我的链接列表

LinkedList<Location> locationData = new LinkedList<>();

这是我的位置类变量

public class Location {

String SA3Code;
String name;

}

问题:我想在方法中插入此 locationData LinkedList

SA3Codename 值列表应插入数据库

我尝试按如下方式插入值,但出现“数据太长”错误

 public void InsertLocations(LinkedList<Location> locationData) throws SQLException {

for (int i = 0; i < locationData.size(); i++) {
statement.executeUpdate("INSERT INTO HomelessInfo.Location (SA3Code, Name) VALUES ('locationData.get(i).SA3Code', 'locationData.get(i).name')");
}
connection.close();
}

错误

Exception in thread "main" com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'SA3Code' at row 1
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:104)
at com.mysql.cj.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1335)
at com.mysql.cj.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2108)
at com.mysql.cj.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1245)
at Homeless.DatabaseUtility.InsertLocations(DatabaseUtility.java:42)
at Homeless.DataFile.readRecords(DataFile.java:98)
at Homeless.COIT20256Assignment2.main(COIT20256Assignment2.java:20)
/Users/SK/Library/Caches/NetBeans/8.2rc/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)

最佳答案

LinkedList locationData;

上面的变量是列表,因此您需要循环列表并根据链表大小进行“N”次sql查询并执行查询

 public void InsertLocations(LinkedList locationData) throws SQLException {
connection.open();
for(customObject : locationData){
StringBuilder sqlquery = new StringBuilder();
sql.append("INSERT INTO HomelessInfo.Location (SA3Code, Name) VALUES ('").append(customObject.column1).append("','").append(customObject.column2).append("'");
statement.executeUpdate(sql.toString());
}
connection.close();

}

根据你的错误,我发现了一段时间 -可能是您的数据库列 - SA3Code 尺寸很小,如 varchar。如果您的数据大小大于列长度,您会遇到以下问题,因此请根据您的需要更新列数据类型。请引用以下数据类型 Database Data Types

谢谢

关于java - 将 LinkedList 值插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62005014/

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