public static final String URL = "jdbc:mysql://url";
public static final String USER = "user";
public static final String PASS = "pass";
public ConnectionFactory()
{
}
public Connection getConnection() {
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
return DriverManager.getConnection(URL, USER, PASS);
} catch (SQLException ex) {
throw new RuntimeException("Error connecting to the database", ex);
}}
public class DbController implements Serializable{
private ConnectionFactory connectionFactory = new ConnectionFactory();
public boolean getCompanyById(int id){
boolean result = false;
try {
Statement stmt = null;
//connect to database
Connection conn = connectionFactory.getConnection();
System.out.println("Connected database successfully...");
stmt = conn.createStatement();
// cast results to Resultset
Resultset resultset = stmt.executeQuery(""SELECT * FROM COMPANY WHERE ID ="+Id+"");
//Iterate through the results creating a new Company object for each set of results and then add them to an ArrayList to filter later on.
while (resultSet.next()) {
Company company = new Company();
company.setId(resultSet.getInt("id"));
company.setCap(resultSet.getDouble("cap"));
company.setDescription(resultSet.getString("description"));
company.setMinimum(resultSet.getDouble("minimum"));
companyList.add(margin);
}
conn.close();
System.out.println("Disconnected from database...");
result = true;
}
catch (SQLException exception){
System.out.println("invalid sql data - remove expense: " + exception.getMessage());
}
return result;
}
1条答案
按热度按时间wgeznvg71#
要从sqldb检索数据,首先需要打开一个连接。创建一个类,如下所示:
然后另一个类来控制与数据库的连接,并获取您可能需要的任何信息。在您的情况下,它是getcompanybyid:
在此之后,您可以从java而不是直接从sql以任何需要的方式转换为html。
希望这有帮助。