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

时间:2018-05-19 13:47:08

标签: java mysql eclipse database-connection

我是java的新手,在从MySQL获取数据时遇到了问题。

我可以建立连接,他们正在等待,但无法从数据库中获取数据

GetCompanyById Java class

GetCompanyById html file

Database table

1 个答案:

答案 0 :(得分:0)

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

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

然后另一个类来控制与DB的连接并获得您可能需要的任何信息。在你的情况下,它是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转换为HTML,而不是直接从SQL转换为HTML。

希望这会有所帮助。