我有一个带有“ spring boot”的应用程序,我需要连接到新的Mysql数据库以读取表。一切正常,我不知道这是否是最好的方法以及如何进行分页。
//我的连接
package com.xxx.xxx.config;
import java.sql.Connection;
import java.sql.SQLException;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class DatabaseAsteriskConfiguration {
private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;
static {
config.setJdbcUrl("jdbc:mysql://xxxxxx/db");
config.setUsername("xxxx");
config.setPassword("xxx");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config);
}
public DatabaseAsteriskConfiguration() {
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
//我的仓库
package com.xxxx.xxxx.asterisk;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.abalia.elser2.config.DatabaseAsteriskConfiguration;
@Repository
public class AsteriskRepository {
Connection conn = null;
Statement stmt = null;
List<AsteriskDTO> list = new ArrayList<>();
public List<AsteriskDTO> loadAll(String inicio, String fin) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DatabaseAsteriskConfiguration.getConnection();
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM cdr WHERE calldate >= '" + inicio + "' and calldate <= '" + fin + "'";
ResultSet rs = stmt.executeQuery(sql);
// STEP 5: Extract data from result set
while (rs.next()) {
AsteriskDTO dto = new AsteriskDTO();
dto.setSrc(rs.getString("src"));
dto.setDst(rs.getString("dst"));
dto.setDuration(rs.getInt("duration"));
dto.setCalldate(rs.getTimestamp("calldate"));
// Display values
System.out.println("src: " + dto.getSrc() + "calldate: " + dto.getCalldate());
list.add(dto);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
return list;
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
}
return list;
}
}
有人可以帮助我,如何以最佳方式连接不是主要应用程序的BBDD并与之交互,以及如何进行分页。