gpt4 book ai didi

java - 我想读取一个 Excel 文件并将数据上传到 PostgresDB 中的一个表中

转载 作者:行者123 更新时间:2023-11-29 13:59:35 27 4
gpt4 key购买 nike

模型类

    import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="employee_details")
public class Employee {
@Id
@Column(name="emp_id")
private int id;
@Column(name="emp_name")
private String name;
@Column(name="location")
private String location;


public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getLocation() {
return location;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public void setLocation(String location) {
this.location = location;
}
}

主类

    public class ReadExcel {
static List<Employee>empList = new ArrayList<Employee>();

public static void main(String[] args){


List<Employee>employees=readExcel("D:\\test.xls");
persistToDB(employees);
}



private static List<Employee> readExcel(String filepath) {
try {
FileInputStream file = new FileInputStream(new
File("D:\\test.xls"));

// Getting the instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);

// Get First sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);

ArrayList myList = new ArrayList();
// Iterate start from the first sheet of the uploaded excel file
Iterator<Row> rowIterator = sheet.iterator();
Employee employee = new Employee();


while (rowIterator.hasNext()) {
Row row = rowIterator.next();

if (row.getRowNum() == 0) {
continue;// skip to read the first row of file
}

// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getColumnIndex() == 0 ) {
employee.setId((int) cell.getNumericCellValue());
empList.add(employee);
System.out.print(cell.getNumericCellValue() + "\t\t");
}
else if (cell.getColumnIndex() == 1 ) {
employee.setName(cell.getStringCellValue());
empList.add(employee);
System.out.print(cell.getStringCellValue() + "\t\t");
}
else if (cell.getColumnIndex() == 2 ) {
employee.setLocation(cell.getStringCellValue());
empList.add(employee);
System.out.print(cell.getStringCellValue() + "\t\t");
}
}
System.out.println("");


}


file.close();

}catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return empList;
}

private static void persistToDB(List<Employee> employees) {
/*SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
*/

Configuration c = new Configuration();
c.configure("/hibernate.cfg.xml");
// SessionFactory holds cfg file properties like // driver props and
// hibernate props and mapping file
SessionFactory sf = c.buildSessionFactory();
// create one session means Connection
Session s = sf.openSession();
// before starting save(),update(), delete() operation we need to
// start TX // starting tx mean con.setAutoCommit(false);
Transaction tx = s.beginTransaction();
try {
for (int i = 0; i < employees.size(); i++) {
Employee emp = employees.get(i);
s.save(emp);
}
tx.commit();
s.close();

} catch (Exception e) {
tx.rollback();
}

}
}

hibernate .cfg.xml

    <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/postgres</property>
<property name="connection.username">postgres</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>


<mapping class="test1.Employee"/>
</session-factory>

</hibernate-configuration>

Employee.java 和 ReadExcel.java 位于 src 下的 test1 包中。

这是我得到的错误

    17:47:44.225 [main] DEBUG o.h.internal.util.EntityPrinter - test1.Employee{id=4,     location=Jayanagara, name=Shwetha}
17:47:44.234 [main] DEBUG org.hibernate.SQL -
insert
into
employee_details
(location, emp_name, emp_id)
values
(?, ?, ?)
Hibernate:
insert
into
employee_details
(location, emp_name, emp_id)
values
(?, ?, ?)
17:47:44.242 [main] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper - could not execute statement [n/a]
org.postgresql.util.PSQLException: ERROR: relation "employee_details" does not exist
Position: 13
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:58) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3067) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3509) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:364) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:356) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:277) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:328) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at test1.ReadExcel.persistToDB(ReadExcel.java:111) [classes/:na]
at test1.ReadExcel.main(ReadExcel.java:27) [classes/:na]
17:47:44.242 [main] WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 42P01
17:47:44.242 [main] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - ERROR: relation "employee_details" does not exist
Position: 13

有人可以帮我解决这个问题吗?我不明白为什么它显示“employee_details”不存在。我在 postgres DB 的 mytestschema 中有这张表,它有三列

    emp_id integer not null
emp_name varchar(255)
location varchar(255)

最佳答案

如果您要访问的表在模式中,则必须通过在模式名称前添加显式地址。例如:

@Table(name="employee_details")

如果将其更改为:可能会更好:

@Table(name="mytestschema.employee_details")

或者,如果您希望 postgres 用户自动查看非标准模式中的数据,您可以修改 postgres 设置以将模式包含在搜索路径中。

alter role postgres set search_path to public, mytestschema;

一旦进入,每次 postgres 连接引用的表/ View /函数时,将首先在公共(public)模式中查找,然后是 mytestschema。通过这种方式,您不必先更改表名来包含架构。

-g

关于java - 我想读取一个 Excel 文件并将数据上传到 PostgresDB 中的一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23542022/

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