adding data to hashmap from database

喜你入骨 提交于 2019-12-11 18:18:29

问题


Hello I am creating an application where I can store data in a Hashmap and List for a shopping cart module.But I want to fetch this data from my MS-Access database.I tried the following code but its not compiling.Please give me guidance.

Code:

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Program {
    public static void main(String [] args){}

    public static HashMap getProductsAsMap() {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con = DriverManager.getConnection("jdbc:odbc:pd");
            ResultSet rs = null;
            Statement st = con.createStatement();
            String sql = ("select * from products");
            rs=st.executeQuery(sql);
            while (rs.next()) { 
                HashMap<String, ProductBean> products= new HashMap<String, ProductBean>();
                String name=rs.getString("pname");
                String desc=rs.getString("pdesc");
                String image=rs.getString("pimage");
                products.put("P1", new ProductBean(name,desc,image));
                return products;
            }
            rs.close();
            st.close();
            con.close();
        }
        catch(Exception e){}   
    }

    public static List getProductsAsList() {
        List<ProductBean> products = new ArrayList<ProductBean>();
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con = DriverManager.getConnection("jdbc:odbc:pd");
            ResultSet rs = null;
            Statement st = con.createStatement();
            String sql = ("select * from products");
            rs=st.executeQuery(sql);
            while (rs.next()) { 
                String name=rs.getString("pname");
                String desc=rs.getString("pdesc");
                String image=rs.getString("pimage");
                products.add(new ProductBean(name,desc,image));
            }
            rs.close();
            st.close();
            con.close();
        }
        catch(Exception e){}
        return products;  
    }
}

I get 2 errors as follows:


回答1:


Your ProductBean class does not have a constructor that takes three strings as parameters.




回答2:


As the error shows, the class ProductBean is missing a constructor with signature with 3 Strings - ProductBean(String, String, String).

Check this class again to match the existing constructor or add a new one to match your code here.




回答3:


It should be like this:

products.add(bean)

bean is the object of ProductBean class ProductBean bean = new ProductBean();



来源:https://stackoverflow.com/questions/12437028/adding-data-to-hashmap-from-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!