JComboBox ExecuteQuery selecting Items error - java

I have 3 jComboBox. The first one is for the Room Type. When I select Room Type on the first jComboBox it must show in the second jComboBox all the available room, but when I select one of the Room Type, an error pops u.p
Here is the code for actionperformed on the first jComboBox
first jComboBox actionperformed*
if(jComboBox13.getSelectedItem().toString().equals("SELECT")){
}else{
try{
String like = jComboBox13.getSelectedItem().toString();
String sql = "Select * From Room_Master\n" +
"inner join Room_Type on Room_Master.Room_Type_ID=Room_Type.Room_Type_ID\n" +
"where Room_Type = '"+like+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jComboBox14.removeAllItems();
jComboBox14.addItem("SELECT");
while(rs.next()){
String add1 = rs.getString("Room_No.");
jComboBox14.addItem(add1);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
}
second jComboBox actionperformed
if(jComboBox14.getSelectedItem().toString().equals("SELECT") | jComboBox14.getSelectedItem().toString().isEmpty()){
}else{
try{
String like = jComboBox14.getSelectedItem().toString();
String sql = "Select * from Bed_Master\n" +
"inner join Room_Master on Bed_Master.Room_ID=Room_Master.Room_ID\n" +
"where [Room_No.] = '"+like+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jComboBox15.removeAllItems();
jComboBox15.addItem("SELECT");
while(rs.next()){
String add1 = rs.getString("Bed_No.");
jComboBox15.addItem(add1);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
}
but after i select another Room type it will work
i tried to remove "combobox.removeAllItems();"
but it will keep addding all the items in the jCombobox
almost 1 week trying to figure it out can someone help please

When you call removeAllItems it fires the actionListener for jComoboBox14
and at this stage it will not have any Items so getSelected will return NULL
change your if to
if(jComboBox14.getItemCount() > 0 && (jComboBox14.getSelectedItem().toString().equals("SELECT") |
jComboBox14.getSelectedItem().toString().isEmpty())){

First of all. You should give your objects variables an useful name:
Ex: jComboBox13 --> JComboBox comboRoomsType = new JComboBox(); or whatever name you prefer.
Then, it would be nice to see all the code involved. I can't see where you initialize the ResultSet or PreparedStatement;
I GUESS the NullPointer comes from the select statement, when trying to retrieve the values.
if(jComboBox13.getSelectedItem().toString().equals("SELECT")){
}else{
try{
String like = jComboBox13.getSelectedItem().toString();
String sql = "Select * From Room_Master RM " +
"inner join Room_Type RT on RM.Room_Type_ID=RT.Room_Type_ID "
+"where Room_Type = '"+like+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jComboBox14.removeAllItems();
jComboBox14.addItem("SELECT");
//you can also check if there are values first.
while(rs.hasNext()){
rs.next();
String add1 = rs.getString("Room_No");
//You can also use
//String add1 = rs.getInt(number of column of <Room_No> );
jComboBox14.addItem(add1);
}
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
}

Related

JDBC error : can not issue executeupdate() for selects

Good day ,
While I am trying to update data after inserting new ones in the database,
This message is showing for me
can not issue executeupdate() for selects
I have checked tutorialspoint.com and codejava and the codes for both update and select are the same and the program is issuing the statement above
Here is my codes
String Sql="Select * from training where trainID=? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("traTitle"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
String Sql="Select * from training where traTitle =? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("trainID"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
String Sql= "UPDATE training SET traTitle ='"+ jTextField2.getText()+"', Type = "+(String) jComboBox1.getSelectedItem()+"', SDate = '"+sqlDate+"', Edate = '"+sqlDate2+"', location = '"+jTextField3.getText()+"',provider = '"+(String) jComboBox1.getSelectedItem()+"',related = '"+jTextArea1.getText()+"',benefits = '"+jTextArea2.getText()+"'important = '"+jTextArea3.getText()+"' WHERE trainID = "+jTextField1.getText()+"";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
Statement st = con.createStatement();
int i =ps.executeUpdate();
if (i>0)
{
JOptionPane.showMessageDialog(null, "Data is Saved");
}
else {
JOptionPane.showMessageDialog(null, "Data is not Saved");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
JOptionPane.showMessageDialog(null, e);
}
Any Solution ?
Statement st = con.createStatement();
int i = ps.executeUpdate();
The problem is here. You are creating a new, unused, Statement, and then trying to call executeUpdate() on the previously prepared statement, which was a SELECT.
This would have been avoided by correctly scoping the variables concerned as method-local. None of them should be instance or static members.

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.

Pull string from sql to java

I am trying to pull a first name and last name from a table in my SQL database. The queries work fine in SQL without the "as First" part and I know the db connection is fine since it works in every other part of the code.
The error I receive is that table "First" does not exist, but it should be looking at firstName and lastName for the table names, not First and Last.
Its inside of a for loop with "i", but those values are correct, playerid = i exists.
try {
String query2 = " SELECT firstName as First from player "
+ "WHERE playerid = ?";
PreparedStatement st2 = db.conn.prepareStatement(query);
st2.setInt(1, i);
ResultSet rs2 = st2.executeQuery();
if (rs2.next()) {
setFirstName(rs2.getString("First"));
}
String query3 = " SELECT lastName as Last from player "
+ "WHERE playerid = ?";
PreparedStatement st3 = db.conn.prepareStatement(query);
st3.setInt(1, i);
ResultSet rs3 = st3.executeQuery();
if (rs3.next()) {
setLastName(rs3.getString("Last"));
}
}
catch (SQLException e) {
e.printStackTrace();
}
Change your code into something like this:
PreparedStatement ps = null;
try {
ps = db.conn.prepareStatement("SELECT firstName, lastName from player "
+ "WHERE playerid = ?");
for (int i = 0; i < MAX_PLAYERS /*<- or what is the loop condition?*/; i++) {
ps.setInt(1, i);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
// should these methods really be called within a loop?
setFirstName(rs.getString("firstName"));
setLastName(rs.getString("lastName"));
}
rs.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (ps != null) {
ps.close();
}
}
Some considerations:
When you're using a PreparedStatement within a loop, you should create the statement once, outside of the loop and then only re-assign the bind variable(s) during each iteration.
You should minimize the number of queries you run against the DB; in your case you should select both the first and last name column in a single query.
It is important to close the resources you open up (the PreparedStatement in this case). My example shows how this is usually done (in the finally block) pre Java 7. Use the try-with-resources statement if you're using a newer Java version.

Java sql text from database

i have a label and i want to upload with text from database, i wrote a method but its show just the first item from database, i want to see all item in column
try {
String sql="SELECT * FROM Arlista";
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
while(rs.next()) {
arlab1.setText(rs.getString("nev"));
}
}catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
while(rs.next()) {
arlab1.setText(rs.getString("nev"));
}
...overwrites the content of arlab each iteration. What you probably want to do is some kind of append to the result for each row;
String result = "";
while(rs.next()) {
if(result.isEmpty()) result = rs.getString("nev");
else result = result + "/" + rs.getString("nev");
}
arlab1.setText(result);

two comboboxes related to each other [duplicate]

This question already has answers here:
Dynamic JComboBoxes
(2 answers)
Closed 8 years ago.
I have two comboboxes ... First one shows the cities of hotels and the second one shows tha hotels name based on the city selected in first combo box. First Combobox is working correctly. second one shows is only for the first selected city. it does not make changes to itself after changing the city in first combo box ! what do I have to add to this code in order to be able to see changes in second combobox by changing the first combobox.
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String City_Selected = jComboBox1.getSelectedItem().toString();
String select_HN = "select name from tbl_Hotel where city = '"+City_Selected+"';";
ResultSet rs = stat.executeQuery(select_HN);
while (rs.next())
{
String hotel_name = rs.getString("name");
// jLabel3.setText(hotel_name);
jComboBox2.addItem(hotel_name);
}//end while
rs.close();
stat.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
Like this ?
jComboBox1.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
jComboBox2.removeAllItems();
fillComboBoxes();
}
});
private void fillComboBoxes(){
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String City_Selected = jComboBox1.getSelectedItem().toString();
String select_HN = "select name from tbl_Hotel where city = '"+City_Selected+"';";
ResultSet rs = stat.executeQuery(select_HN);
while (rs.next())
{
String hotel_name = rs.getString("name");
// jLabel3.setText(hotel_name);
jComboBox2.addItem(hotel_name);
}//end while
rs.close();
stat.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Categories