我想创建一个 Java GUI 程序。
该程序应允许用户添加项目(标题、价格)。当他们添加一个项目时,该项目必须添加到一个 mySql 数据库以及一个项目对象。然后需要将此项目对象存储在集合中。
Java 项目对象:
import java.util.*;
import java.io.Serializable;
class Items implements Serializable{
private String title;
private String price;
public Items(String t, String p) {
title = t;
price = p;
}
public void setTitle(String t) {
title = t;
}
public String getTitle() {
return title;
}
public void setPrice(String p) {
price = p;
}
public String getPrice() {
return price;
}
}
店铺
import java.util.*;
import java.io.Serializable;
import java.rmi.*;
import java.rmi.server.*;
import java.sql.*;
class Shop extends UnicastRemoteObject implements ShopInterface, Serializable {
//Create Array to Store Items and Users
ArrayList<Items> arrayItems;
//Database connection data
Connection conn = null; // connection object
private final String database = "Shop";
private final String user = "";
private final String password = "";
private final String url = "jdbc:mysql:///" + database;
protected Shop() throws RemoteException {
arrayItems = new ArrayList<Items>();
//Load the driver
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//Establish Connection
try {
conn = DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Shop Created and Database Connection Completed");
}
//Add Items to Shop
public void additems(String t, String p)
throws RemoteException {
//SQL Insert Statement
String insertSQL = "INSERT INTO ShopItems(title, price) VALUES('" +
t + "','" + p + "')";
//Try Insert
try {
Statement stmt = conn.createStatement();
int res = stmt.executeUpdate(insertSQL);
arrayItems.add(new Items(t, p));
}
catch(SQLException se) {
System.err.println(se);
}
}
}
这是正确的方法吗?像这样的东西会起作用吗?(没有测试过这个)