如何从文件中将一堆记录插入MySQL 我正在为一个带有java和JDBC的库编写这个应用程序我到目前为止已经有了这个。
该程序能够导出包含大量书籍的文件,我想加载该文件的内容,但在插入数据之前,我必须验证每条记录并显示插入的记录数量。 当我跑步说 连接太多 我该怎么办?
public class BookDAO extends BaseDAO {
private static final String SELECT_SAME = "SELECT COUNT(*) AS counter
FROM Book WHERE "name=? AND ISBN=?";
...
public void create(Book book) throws SQLException {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(SQL_INSERT);
ps.setLong(1, com.getISBN());
ps.setString(2, com.getName());
ps.executeUpdate();
} finally {
close(ps);
close(conn);
}
}
...
public boolean isRegistered(Book book) throws SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
int counter = 0;
try {
ps = conn.prepareStatement(SELECT_SAME);
ps.setLong(1, book.getISBN());
ps.setString(2, book.getName());
rs = ps.executeQuery();
if (rs.next()) {
counter = rs.getInt("counter");
}
} catch (SQLException e) {
LOGGER.warn("BookDAO fail to check if is registered :" + e);
} finally {
close(rs);
close(ps);
close(conn);
}
return counter < 1;
}
public List<Number> loadFromFile(List<Book> book) throws SQLException {
PreparedStatement ps = null;
int added = 0;
int notAdded = 0;
List<Number> values = new ArrayList<>();
try {
this.conn.setAutoCommit(false);
ps = conn.prepareStatement(INSERT);
for (Book book : books) {
ps.setISBN(1, book.getISBN());
ps.setString(2, book.getName());
ps.addBatch();
ps.clearParameters();
added++;
}
ps.executeBatch();
this.conn.commit();
values.add(added);
values.add(notAdded);
} catch (SQLException e) {
LOGGER.warn("BookDAO fail getting the books from file :" + e);
} finally {
close(ps);
this.conn.setAutoCommit(true);
close(conn);
}
return values;
}
... more methods
BaseDAO类包含。
public class BaseDAO {
protected Connection conn;
public Base2DAO() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "user", "");
LOGGER.info("Connected to database");
} catch (ClassNotFoundException | SQLException e) {
LOGGER.fatal("Database not found!" + e);
}
}
protected void close(Connection cnn) throws SQLException {
...
}
protected void close(PreparedStatement ps) throws SQLException {
...
}
protected void close(ResultSet rs) {
...
}
public Connection getConnection() {
return conn;
}
public void close() throws SQLException {
conn.close();
}
}
所以在主应用程序中我有这个
public static void main(){
...
ArrayList<Book> bookList = (ArrayList<Book>) xstream.fromXML(xml);
List<Book> checkedBooks = new ArrayList<>();
//the problem begins here
for (Book book : bookList) {
if (new BookDAO().isRegistered(book)) {
checkedBooks.add(book);
}
}
List<Number> result = new BookDAO().loadBooksFromFile(checkedBooks);
results += ("\nNew records:");
results += (String.valueOf(result.get(0)));
results += ("\nRegistered previously:");
results += (String.valueOf(bookList.size() - checkedBooks.size()));
}
感谢。