How to insert to database from combo box? - java

I'm just trying to make some combo box with value from database and I can choose it and insert it to database, but I had some error message. How to resolve that?
Here my code:
private void btnInputDataProdukActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = "insert into tb_produk (produk_kat_id,produk_nm,produk_gndre,produk_size,produk_hrg) values (?,?,?,?,?)";
try {
PreparedStatement stat = conn.prepareStatement(sql);
stat.setString(1, txtNamaProduk.toString());
String valueKat = cbKatProduk.getSelectedItem().toString();
stat.setString(2, valueKat);
String valueGender = cbGender.getSelectedItem().toString();
stat.setString(3, valueGender);
stat.setString(4, txtUkuran.toString());
stat.setString(5, txtHarga.toString());
stat.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Berhasil Disimpan");
kosong();
dataTable();
lebarKolom();
txtNamaProduk.requestFocus();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Data Gagal Disimpan" + e);
}
}
The combo box with value from DB
public void tampil_combo(){
String sql = "select kat_id from tb_kategori";
try {
java.sql.Statement stat = conn.createStatement();
ResultSet res = stat.executeQuery(sql);
while (res.next()) {
Object[] ob = new Object[3];
ob[0]=res.getString(1);
cbKatProduk.addItem((String) ob[0]);
}
res.close();stat.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}

produkt_kat_id is defined as an int in your database. But with
stat.setString(1, txtNamaProduk.toString());
you are setting a string. Also note that you are calling toString() on the combo box and not the selected value.
So you need to convert the selected value into an integer:
stat.setString(1, Integer.parseInt(txtNamaProduk.getSelectedItem()));
You would still need to add some error handling in case txtNamaProduk.getSelectedItem() returns null or in case the combo box can also contain other values than integers.
You will also need to change your code for the other fields that are defined as integers in the database.

Related

How to delete row from bound JTable?

I have a JTable bound to MySQL. I already have done code to insert data.
But i don't know how to delete.
I have this sample delete method that works in other simple projects.
public String deleteItem(String name) {
String answer = "";
try {
Connection con = Connect.getConnection();
String sql = "Delete FROM item where name = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.executeUpdate();
ps.close();
con.close();
answer = "OK";
} catch (Exception e) {
answer = e.toString();
}
return answer;
}
Even when I worked with an unbound table I have done this remove row from jtable that did well for me.
But now its a table bound to MySQL and I can't find a way to delete row... already searched on the internet. Found nothing.
PS: i'm using netbeans. i right-clicked jtable > bind > elements , to bind table.
Oh, I found a way!
First, I changed my deleteItem method, to delete by id
ItemDAO.java
public String deleteItem(int ID_item) {
String answer = "";
try {
Connection con = Connect.getConnection();
String sql = "Delete FROM item where ID_Item = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, ID_item);
ps.executeUpdate();
ps.close();
con.close();
answer = "OK";
} catch (Exception e) {
answer = e.toString();
}
return answer;
}
Then the action in delete button goes like this.
Form.java
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
int column = 0; // get the first column which is ID_Item
int row = tableItem.getSelectedRow(); //get row selected by user
int value = (int) tableItem.getModel().getValueAt(row, column); // store ID_Item value
String answer = new ItemDAO().deleteItem(value); // call up deleteItem method
if(answer.equals("OK")) {
System.out.println("OK"); // just for test
itemList.clear(); // this is needed to update the bound table after Insert/Delete/Update etc
itemList.addAll(itemQuery.getResultList()); // same as above comment
}else{
System.out.println("ERROR"); // just for test.
}
Maybe isn't the most beautiful way to do it, but it works.

Java-Output all the columns and rows of a ResultSet

ta.setText is a TextArea where I want to show all my data from the database, after a button click. But with rs.get("name") I just output one value and it is always the last. How can I print out the whole table from the database, so all the information which are stored there?
try { String newquery = "SELECT * FROM kunden";
java.sql.PreparedStatement ps = con.prepareStatement(newquery);
rs = ps.executeQuery(newquery);
while (rs.next()){
ta.setText(rs.getString("name"));
ta.setText(rs.getString("nachname"));
}
}// try
catch(Exception e1) {
JOptionPane.showMessageDialog(null, "fail");
}
}//actionperformed
Either you build a string an then set that string using setText()
StringBuilder builder = new StringBuilder();
while (rs.next()) {
builder.append(rs.getString(“name”));
builder.append(“ “);
builder.append(rs.getString(“nachname”));
builder.append(“\n“);
}
ta.setText(builder.toString());
Or you use the append method that exists for TextArea
while (rs.next()) {
ta.append(rs.getString(“name”));
ta.append(“ “);
ta.append(rs.getString(“nachname”));
ta.append(“\n“);
}

How to remove data in database from jTable?

I want to remove the data in database from jtable. I have 1 jTextField and 1 jButton. So when i click this selected row in table, the primary key wont set in my jTextField.
Is it possible to remove the data in database from jtable without jTextField and just a button?
Heres my code
try {
int row = table.getSelectedRow();
String id_ = (table.getModel().getValueAt(row, 1)).toString();
String sql ="SELECT id FROM 'mycredentials.sales' WHERE id= "+id_+"'";
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
PreparedStatement pst = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
jFrame_removeP.setText(rs.getString("id"));
}
} catch (SQLException e1) {
System.err.println(e1);
}
Random id number appears in my jTextField. And my table code is:
String name = jFrame_pName.getText().trim();
String price = jFrame_pPrice.getText().trim();
String quantity = jFrame_quantity.getText().trim();
String total = jFrame_total.getText().trim();
String st[] = {name, price, quantity, total};
model.addRow(st);
jFrame_gTotal.setText(Integer.toString(getSum()));
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
Statement s = (Statement) connection.createStatement();
String sql = "INSERT INTO mycredentials.sales (name, price, quantity, total) VALUES ('"+jFrame_pName.getText()+"', '" + jFrame_pPrice.getText() + "','"+jFrame_quantity.getText()+"','"+jFrame_total.getText()+"')";
s.executeUpdate(sql);
} catch (SQLException e1) {
System.err.println(e1);
}
And my remove button is:
DefaultTableModel model1 = (DefaultTableModel) table_1.getModel();
int selectedRowIndex = table_1.getSelectedRow();
model1.removeRow(selectedRowIndex);
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
Statement ps = (Statement) connection.createStatement();
String sql = "DELETE from mycredentials.sales where id ='" + jFrame_removeP.getText() + "'";
ps.executeUpdate(sql);
} catch (Exception ex) {
System.err.println(ex);
}
Do you mean like this? I didn't get exactly what you needed. Hope this helps.
private void deleteBtnActionPerformed(java.awt.event.ActionEvent evt) {
String deleteQuery = "DELETE FROM SAMPLE WHERE USER_ID = ?";
try (Connection myCon = DBUtilities.getConnection(DBType.JDBC);
PreparedStatement myPs = myCon.prepareStatement(deleteQuery);){
myPs.setInt(1,userID);
myPs.executeUpdate();
JOptionPane.showMessageDialog(null,"Records deleted");
}//end of try
catch (SQLException ex) {
DBUtilities.processException(ex);
}//end of catch
}
After search a record. You just click a record in the Jtable you want to delete. And just hit the Delete Button simple as that.
Just use a refresh method here if you want to remove the selected row. Fix your statement much better if you use Prepared Statement than Statements to avoid SQL injection.

Printing a query from a database

I am trying to access a database and print off a query.
I am trying to access a DEVICE table and print off the DEVICE_ID, but i am unsuccessful so far.
Here is my code at the moment;
public static void main(String[] args) throws FileNotFoundException {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
Preferences sysRoot = Preferences.systemRoot();
Preferences prefs = sysRoot.node("com/davranetworks/zebu");
url = prefs.get("dburl", "jdbc:hsqldb:E:\\eem\\eemdb");
} catch (Exception e) {
e.printStackTrace();
}
Connection c = getConnection();
try {
c.setAutoCommit(true);
Statement s = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = s.executeQuery("SELECT * FROM eem_db.device");
ResultSet deviceId = s.executeQuery("select device_id from eem_db.device");
System.out.println(deviceId);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection c = null;
try {
c = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println("Error initialising connection" + e);
}
return c;
}
The returned value is org.hsqldb.jdbc.JDBCResultSet#1d3d68df.
I don't know what this value relates to as I was expecting 3 integer values.
Can anyone help me on this?
You have to iterate over the rows contained in the ResultSet and for each row get the column you want:
ResultSet deviceIdRS = s.executeQuery("select device_id from eem_db.device");
while(deviceIdRS.next()) {
System.out.println(deviceIdRS.getString("device_id"));
}
You must use the ResultSet getXXX method that correspond with your column type, for example, getInt, getString, getDate...
That ResultSet deviceId is actually an object contains rows of result from your sql, so you only can see the memory address when you print it out.
You need something like:
while(deviceId.next()){
System.out.print(deviceId.getInt(1));
}
s.executeQuery("select device_id from eem_db.device"); is returning a resultSet, you must find out the value from result set.
like
int device_id = resultset["deviceId"];
while (deviceId.next())
{
// Printing results to the console
System.out.println("device_id- "+ deviceId.getInt("device_id");
}
iterate object using resultset.
You are printing object of ResultSet, it won't give you the right values.
You need to iterate the loop like below
while(deviceId.next()) {
int integerValue = deviceId.getInt(1);
System.out.println("content" + integerValue)
}
deviceId.close();
s.close();

Retrieving data based on the ID java

i wanted to retrieve the data from the database with ID.. So, i wanted to do like this: i have number on my combobox 1 to 4. Whenever i select 1 in combobox, the textbox firstname and lastname text will be change based on the selected id. How do i do that?
I already tried like this, but it won't work:
private void Edit(Connection conn, Statement state, ResultSet result)
{
try
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String url = "jdbc:odbc:Database";
conn = DriverManager.getConnection(url);
String query = "select FirstName, LastName, Status, JoinedDate from Customer where ID = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, jComboBox1.getSelectedIndex());
result = statement.executeQuery();
while(result.next())
{
jTextField3.setText("FirstName");
jTextField2.setText("LastName");
jTextField3.setText("Status");
JoinedDateLabel.setText("JoinedDate");
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
_sound.PlaySound(2);
_infoBox.ShowMessageBox(e.getMessage(), "Error", 2);
_reminder = new Reminder(1);
JOptionPane.showOptionDialog(null, "Program will be closed due to error!", "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);
System.exit(0);
}
Thank you
Try this
while(result.next())
{
jTextField1.setText(result.getString("FirstName"));
jTextField2.setText(result.getString("LastName"));
jTextField3.setText(result.getString("Status"));
JoinedDateLabel.setText(result.getString("JoinedDate"));
}
All you're doing with your current code is setting the text to the strng literal "FirstName". You need to actually retrieve the data from the ResultSet and set the text as that data.
Also, note JComboBox indices are 0 based. So if you are selecting the first index, it would return 0. You should make sure (in your case) that the db has Id's of 0,1,2,3

Categories