无法使用html和连接池从数据库获取数据

zwghvu4y  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(367)

我是java新手,从mysql获取数据时遇到问题。
我可以建立连接,他们正在等待,但无法从数据库中获取数据


wgeznvg7

wgeznvg71#

要从sqldb检索数据,首先需要打开一个连接。创建一个类,如下所示:

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);
            }}

然后另一个类来控制与数据库的连接,并获取您可能需要的任何信息。在您的情况下,它是getcompanybyid:

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;
        }

在此之后,您可以从java而不是直接从sql以任何需要的方式转换为html。
希望这有帮助。

相关问题