Populate JCombobox values depending on another JCombobox - java

I have two JComboboxes A and B, so if I select any item form A then values related to the item selected in A should fill in JCombobox B. I tried this but get an error:
java.lang.ArrayIndexOutOfBoundsException: 0
at pst.setString(1, client.getSelectedItem().toString());
try
{
String query="select `User_Name` from Client where `Client_Name`='?' ";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1, client.getSelectedItem().toString());
ResultSet rs=pst.executeQuery();
user.addItem("--Select--");
while(rs.next())
{
user.addItem(rs.getString("User_Name"));
}
// return;
System.out.println(query);
}
catch(Exception g)
{
g.printStackTrace();
}

The PresparedStatement takes care of quoting the parameter, when you use setString()
Try
String query="select User_Name from Client where Client_Name = ?";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1, String.valueOf(client.getSelectedItem()));
I guess that when you use '?' the prepared statement does not count this as parameter and this is why you get the IndexOutOfBounce

you have done a mistake ,
no need to use '?' , it should be just Client_Name=?

Related

How to parse values for the result set's .equals function?

image showing my jFrame
I am making a frame which shows records in the sql table one-by-one using text fields as shown. While writing the code for the next button, I need to know the position of the result set to go to the next record. For this purpose, I used a do-while loop with an "if" condition. Following is my code:
try{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String url="jdbc:mysql://localhost/MYORG", userid="root", pwd="shreyansh";
conn=DriverManager.getConnection(url,userid,pwd);
stmt=conn.createStatement();
String query="select * from emp;";
rs=stmt.executeQuery(query);
String search=jTextField1.getText();
String search1=jTextField2.getText();
double search2=Double.parseDouble(jTextField3.getText());
String search3=jTextField3.getText();
rs.first();
do{
if(rs.equals(new Object[] {search, search1, search2, search3}))
break;
}while(rs.next());
rs.next();
String nm=rs.getString("Name");
String desg=rs.getString("Designation");
double pay=rs.getDouble("Pay");
String city=rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(pay + "");
jTextField4.setText(city);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
But it shows an error "after end of Result Set".
Please help me with this.
Any suggestions to make my code better are also welcome.
Thanks in Advance!!
You can't use ResultSet.equals for this, because that is not what the Object.equals contract is for. It is for checking if an object is equal to another object of the same (or at least compatible) type. A ResultSet will therefor never be equal to an array of object values.
It looks like you want to select a single row from the emp table that matches your search values, in that case the correct solution is to ask the database for only that row. Selecting all rows and then filtering in your Java application is very inefficient, because the database has to send all rows to your application, while finding data is exactly what a database is good at.
Instead, you should use a where clause with a prepared statement:
try (Connection connection = DriverManager.getConnection(url, userid, pwd);
PreparedStatement pstmt = connection.prepareStatement(
"select * from emp where Name = ? and Designation = ? and Pay = ? and City = ?")) {
pstmt.setString(1, search);
pstmt.setString(2, search1);
pstmt.setDouble(3, search2);
pstmt.setString(4, search3);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next() {
String nm = rs.getString("Name");
String desg = rs.getString("Designation");
double pay = rs.getDouble("Pay");
String city = rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(String.valueOf(pay));
jTextField4.setText(city);
} else {
// handle not found case
}
}
}

How to select data from table with parameter

Trying to get all the data in the row with the specified name string. Im getting a syntax error right now. myConn is declared in the constructor and name is a varchar in the database named organization. My error code is "Can not issue executeUpdate() or executeLargeUpdate() for SELECTs"
public void getOrgByName(String name){
try {
st = myConn.createStatement();
String query = "SELECT * FROM organization WHERE name = ?";
PreparedStatement preparedStmt = myConn.prepareStatement(query);
preparedStmt.setString(1, name);
preparedStmt.executeUpdate();
}catch(Exception e){
System.out.println("Cannot get org name" + e);
}
}
You’re performing a select query so you’ll need to use executeQuery i.e
Replace this:
preparedStmt.executeUpdate();
With this:
ResultSet rs = preparedStmt.executeQuery();

Having Difficulty In Searching on My JAva Program

I want to search some data from database and set it to jtable. So far I have written this code:
try
{
String sql="select * from hotelinfo where Hotel_Name=?;
pst=conn.prepareStatement(sql);
pst.setString(1,searchtxt.getText());
rs=pst.executeQuery();
hotelinfo.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
this code is working but gives only one row i want whole rows which is related to my search
As to your question, you should use like keyword in your select query instead of = sign.
Try with below code:
String sql = "select * from hotelinfo where Hotel_Name LIKE ?";
pst= connection.prepareStatement(sql);
pst.setString(1, "%" + searchtxt.getText() + "%");
rs= preparedStatement.executeQuery();

Search DATA in Jtable

I am implementing a search method, i want to search a data in a Jtable ( wich contains 2 columns id and name) based in id and name both. Till now I can search using just one of, id or name but cannot do that using them both. I tried a solution, but it is not working it just search for the last one ( id or name). For example if i start with try and catch by name and then id, it only goes with id search. And if I start with id and the name, it searches just by name. Can u help me please.
The code :
`private void textField1KeyReleased(java.awt.event.KeyEvent evt) {
PreparedStatement pst=null;
ResultSet rs=null;
if (textField1.getText().length() > 0){
try{
String sql = "select * from compte_utilisateur where nom=?";
pst=maConnexion.ObtenirConnexion().prepareStatement(sql);
pst.setString(1, textField1.getText());
rs=pst.executeQuery();
TableUtilisateur.setModel(DbUtils.resultSetToTableModel(rs));}
**catch(Exception e){JOptionPane.showMessageDialog(null, e);}
try{
String sql = "select * from compte_utilisateur where id_utilisateur=?";
pst=maConnexion.ObtenirConnexion().prepareStatement(sql);
pst.setString(1, textField1.getText());
rs=pst.executeQuery();
TableUtilisateur.setModel(DbUtils.resultSetToTableModel(rs));}
catch(Exception e){JOptionPane.showMessageDialog(null, e);}
}
else update_table();
}`**
Use just one SQL call passing the same value from the field twice
select * from compte_utilisateur where nom=? or id_utilisateur=?
You should to add jar/folder this rs2xml.jar in your project
String sql="Select * From Inventarizimi where Regjistrimi=?";
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con= (Connection) DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","Inventarizimi"); PreparedStatement preStatement = con.prepareStatement(sql); preStatement.setString(1, txtRegjistrimi.getText());
ResultSet result = preStatement.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(result));

Is there a way to retrieve the autoincrement ID from a prepared statement

Is there a way to retrieve the auto generated key from a DB query when using a java query with prepared statements.
For example, I know AutoGeneratedKeys can work as follows.
stmt = conn.createStatement();
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
However. What if I want to do an insert with a prepared Statement.
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql);
//this is an error
stmt.executeUpdate(Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
//this is an error since the above is an error
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
Is there a way to do this that I don't know about. It seems from the javadoc that PreparedStatements can't return the Auto Generated ID.
Yes. See here. Section 7.1.9. Change your code to:
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.executeUpdate();
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
There's a couple of ways, and it seems different jdbc drivers handles things a bit different, or not at all in some cases(some will only give you autogenerated primary keys, not other columns) but the basic forms are
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
Or use this form:
String autogenColumns[] = {"column1","column2"};
stmt = conn.prepareStatement(sql, autogenColumns)
Yes, There is a way. I just found this hiding in the java doc.
They way is to pass the AutoGeneratedKeys id as follows
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
I'm one of those that surfed through a few threads looking for solution of this issue ... and finally get it to work. FOR THOSE USING jdbc:oracle:thin: with ojdbc6.jar PLEASE TAKE NOTE:
You can use either methods:
(Method 1)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
myPrepStatement = <Connection>.prepareStatement(yourSQL, Statement.RETURN_GENERATED_KEYS);
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
java.sql.RowId rid=rs.getRowId(1);
//what you get is only a RowId ref, try make use of it anyway U could think of
System.out.println(rid);
}
} catch (SQLException e) {
//
}
(Method 2)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
//IMPORTANT: here's where other threads don tell U, you need to list ALL cols
//mentioned in your query in the array
myPrepStatement = <Connection>.prepareStatement(yourSQL, new String[]{"Id","Col2","Col3"});
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
//In this exp, the autoKey val is in 1st col
int id=rs.getLong(1);
//now this's a real value of col Id
System.out.println(id);
}
} catch (SQLException e) {
//
}
Basically, try not used Method1 if you just want the value of SEQ.Nextval, b'cse it just return the RowID ref that you may cracked your head finding way to make use of it, which also don fit all data type you tried casting it to! This may works fine (return actual val) in MySQL, DB2 but not in Oracle.
AND, turn off your SQL Developer, Toad or any client which use the same login session to do INSERT when you're debugging. It MAY not affect you every time (debugging call) ... until you find your apps freeze without exception for some time. Yes ... halt without exception!
Connection connection=null;
int generatedkey=0;
PreparedStatement pstmt=connection.prepareStatement("Your insert query");
ResultSet rs=pstmt.getGeneratedKeys();
if (rs.next()) {
generatedkey=rs.getInt(1);
System.out.println("Auto Generated Primary Key " + generatedkey);
}

Categories