我是 Java 新手。我已经创建了 Products 类型的通用列表,如何将其添加到数据库中。该列表包含 Products 的对象,数据库中的列是 Products 类的字段。即使我通过 listvariable.get(0) 等分隔列表,我也会得到对象,而不是对象内部的值。
更新:使用 for 循环插入并获取每个对象的字段。有没有更好的方法
import java.util.*;
public class Products {
public static List <Products> li = new ArrayList<Products> ();
static
{
Products o = new Products (1,"Milky Way",12.0,7); // Static because
Products o1 = new Products (2,"Dairy Milk",50.0,17); // these entries
Products o2 = new Products (3,"Borunville",70.0,27); // are mandatory
Products o3 = new Products (4,"Lindt",1022.0,107);
li.add(o);
li.add(o1);
li.add(o2);
li.add(o3);
}
int ItemCode;
String ItemName;
double UnitPrice;
int AvailableCount;
public int v=3;
Products()
{}
Products (int x,String y, double c, int d)
{
ItemCode=x;
ItemName=y;
UnitPrice=c;
AvailableCount=d;
}
public String toString ()
{
return ( ItemName+" "+ ItemCode +" "+ UnitPrice + " "+ AvailableCount);
}
void addProduct()
{
li.add(this);
}
public List <Products> initProducts()
{ return li;
}
}
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
public class Shopowner {
public static void main (String ...args)
{
Products o = new Products(6,"Eclairs",12.33,5);
o.addProduct();
System.out.println(new Products().initProducts());
try
{
Connectivity.establishConnection(); // static method for db url and drivers
for (int i =0;i<4;i++)
{
Products x=Products.li.get(i);
String name=x.ItemName;
int id= x.ItemCode;
int count =x.AvailableCount;
double price = x.UnitPrice;
PreparedStatement stm = Connectivity.con.prepareStatement("insert into Products_tbl values (?,?,?,?)");
stm.setInt(1, id);
stm.setString(2, name);
stm.setDouble(3,price);
stm.setInt(4, count);
stm.executeUpdate();
}
}
catch(Exception e)
{e.printStackTrace();}
//System.out.println(new Products().li);
}
}