i am creating a small inventory control system for my final year. instead of add category name add category id in to the database i don't know how add do the task .what i tried so far i attached.
i load the category in to jComboBox1
public void LoadCategory()
{
try {
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/javapos","root","");
insert = con1.prepareStatement("SELECT * FROM category");
ResultSet rs = insert.executeQuery();
jComboBox1.removeAllItems();
while(rs.next())
{
jComboBox1.addItem(rs.getString(2));
}
}
catch (Exception e) {
}
}
add the record into the product table.
String productname =txtproduct.getText();
String productdec =txtdec.getText();
int categoryid =jComboBox1.getSelectedItem().toString();
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/javapos","root","");
insert = con1.prepareStatement("insert into product (productname,description,category)values(?,?,?)");
insert.setString(1,productname);
insert.setString(2,productdec);
insert.setString(3,categoryid);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Sucsessfully Saved");
I guess (from your question) your table category
should contains such columns:
id
- int autoincremented (implicit)productname
- ...description
- ...name
- name of a category
Next. You need to create a custom JComboBox
item's type. For the example:
class CategoryItem
{
int id;
String name;
// add other fields if you want...
CategoryItem(int id, String name)
{
this.id = id;
this.name = name;
}
String toString()
{
return name;
}
}
When you're loading the records from the table you're creating the CategoryItem
class objects and append them to JComboBox
, like this:
public void LoadCategory()
{
//...
jComboBox1.removeAllItems();
while(rs.next())
{
// rs.getInt('id') - id value of the category record
jComboBox1.addItem( CategoryItem( rs.getInt('id'), rs.getString('name') );
}
//...
}
When a new record to be inserted into the table the database set and fill its id
with a new autoincremented value implicitly:
Category categoryItem = (CategoryItem)jComboBox1.getSelectedItem();
insert = con1.prepareStatement("INSERT INTO product (productname, description, name) VALUES (?,?,?)");
insert.setString(1, productname);
insert.setString(2, productdec);
insert.setString(3, categoryItem.name);
To get the last record create a query (example for MySQL
):
getLastCategory.prepareStatement("SELECT * FROM category WHERE id = LAST_INSERT_ID()");
If you need to update the category's data you get CategoryItem
object and take its id
:
CategoryItem item = (CategoryItem)jComboBox1.getSelectedItem();
int id = item.id;
query.prepareStaement("UPDATE category SET productname = ? WHERE id = ?");
query.setString(1, "new product name");
query.setInt(2, id);