I'm trying to display database item into a JComboBox and this is my code.
public static void checkItemName(){
Connection conn = SQLite.SQLite();
String sql = "select itemname from item";
try{
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
String list = resultSet.getString("itemname");
purcItemName.addItem(list);
conn.close();
}
} catch (SQLException lol){
System.out.println(lol.toString());
}
}
I did declare static JComboBox purcItemName; and purcItemName = new JComboBox();
The method/function will be called then user press login button.
The problem I'm having now is that, it only shows one item while my database has multiple items.
Anyone got an idea why?
Vector v = new Vector();
while (resultSet.next()){
String list = resultSet.getString("itemname");
v.add(list);
}
conn.close();
purcItemName.setModel(new DefaultComboBoxModel(v));
store the data you got from database in a vector object and once that is completed set the vector object in your combobox as a new model. try this one
and don't close the connection inside your loop.
you are closing connection inside resultSet.next() check, put the conn.close() outside, to the end
Related
I have a problem with JComboBox. It's blocking another field in a frame meant to display another value that is linked through a foreign key in a database, a value that depends on the combo box already pop out. But somehow, after the user clicks the combo box it is blocking another field. The app is using MySql.
Here's the code:
ComboBox method to fill value from DB
public void comboBoxBerat(){
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
try {
sql = "SELECT * FROM weight_of_services";
rs = stat.executeQuery(sql);
while (rs.next()) {
jComboBoxBerat.addItem(rs.getString("weight"));
}
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
Action when selection is made from combo box, its get the value that linked with foreign key
private void jComboBoxBeratActionPerformed(java.awt.event.ActionEvent evt) {
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
String item = (String)jComboBoxBerat.getSelectedItem();
String sql = "SELECT price FROM weight_of_services WHERE weight = ?";
try {
pst = con.prepareStatement(sql);
pst.setString(1, item);
rs = pst.executeQuery();
if (rs.next()) {
String price = rs.getString("price");
txtHargaBerat.setText(price); //put value from combobox to txtField
}
con.close();
} catch (Exception e) {
}
}
The problem after I select from the box its blocking another field.
This is the combo box problem in the frame
It's solved. This because i am using jpanel for customizing color for the frame. Its just so messed up with the stacking one panel on top of the other one. That's why my dropdown list get blocked. So what I did, removed all the panel. Custom and sorting it more carefully and tidy from the start.
private void next_contactActionPerformed(java.awt.event.ActionEvent evt) {
String name, lName, add, em, cell = null;
try {
String Url = "Jdbc:Odbc:DirDSN";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(Url,"sa","mysql");
//Statement st = con.createStatement();
String sql = "SELECT * FROM PersonInformation";
PreparedStatement pstmt = con.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
name = rs.getString("First_Name");
lName = rs.getString("Last_Name");
add = rs.getString ("Address");
em = rs.getString("Email_Id");
cell = rs.getString("cell#");
jTextField2.setText(name);
jTextField3.setText(lName);
jTextField4.setText(add);
jTextField5.setText(em);
jTextField10.setText(cell);
}
con.close();
} catch(Exception sqlEx) {
System.out.println(sqlEx);
} finally {
}
}
I have written this next function for next button. I want when I click the next button the rs.Next() returns a new record of table on the screen. Now I am facing the problem that each time when I click the next button I get the first row of the table. I have also used while (rs.Next()) but it returns me the last row of table each time I click the next button. Please tell me how I can write this function such that each time I call this function it returns a new record from the table.
Change ResultSet rs to a member variable or save the position you're in and use it as a parameter for the method (see LIMIT).
At the moment, you create a new ResultSet with every click, always starting at index 0.
I want to fill the jComboBox with values from database. and these values depend on the text written in the textfield.
eg: if I write a in the texfield, the combobox will have all values starting with a. The values are from a databse
Here's my code:
private void FillCombo(){
String url = "jdbc:mysql://localhost:3306/pharmacy";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "test";
String sql = "select medicinename from medicine where medicinename like '%"+jTextField5.getText()+"%'";
try{
Class.forName(driver).newInstance();
System.out.println("1");
Connection con = (Connection)DriverManager.getConnection(url,user,pass);
System.out.println("Connected");
Statement st=(Statement) con.createStatement();
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while(rs.next()){
String name = rs.getString("medicinename");
jComboBox1.addItem(name);
}
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}}
I want not just one caracter eg: if i write a, as, asp it fill aspirine myproblem is that the combobox is already filled. want it empty when i start.
Simply use JComboBox#removeAllItems() to removes all items from the item list on each stroke of any key in the JTextField.
Points to Remember
Don't load driver each time you enter a new character. Move it outside the FillCombo() method.
Use PreparedStatement instead of using single quoted query string that may cause issue. Find a sample on Using Prepared Statements
Don't forget to close the resources such as connection, result set and statement.
Use finally block to handle it or Read more about Java7 -The try-with-resources Statement
Ok So I have a program where I add new Players to a database, and where I load them users into a list. The problem is when I delete a user, then go to add a new user the new player gets added in to where the old user was. Basically because that spot is free now and I use:
rs.moveToInsertRow();
is there a way that when adding a new player it 'Always' adds to the end of the the database. Like when you delete a row from table to make the database compress so it has no gaps?
here is the code:
public static void Save() { try {
String Name = "#####";
String Pass= "#####";
String Host = "######";
Connection con = DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s", Host, "####", "####"),
Name, Pass);
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM Accounts";
ResultSet rs = stmt.executeQuery(sql);
rs.moveToInsertRow( );
String userName= TestForm.UsernameTextField.getText(); //make this equal to whats in textfield
String password= TestForm.PasswordTextField.getText(); //make this equal to whats in textfield
String insertQuery="insert into Accounts (`Username`,`Password`) values ('"+userName+"','"+password+"');";
stmt.executeUpdate(insertQuery);
stmt.close();
rs.close();
}
catch(Exception e)
{
System.out.println("ERROR");
e.printStackTrace();
}
What's your table create statement? SHOW CREATE TABLE Accounts ;
Seems like an AUTO_INCREMENT integer primary key in the table would help your issue.
I want to use this vector as DataSource for my Jtable. There are four columns here (ADI, SOYADI, BABA ADI, ANA ADI). ResultSet is adding every row to vector named _kisivector. This is my DataSource.
But I don't want to get whole records at start. I want to get only 5 records from this vector. Then there will be 2 button, back and forward. When I click Forward it will go for other 5 record. And when I click back button, it will go for 5 previous record.
Is there any example for this?
private Vector getSonuc(String _ad){
Vector _kisivektor = new Vector();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#xx.xx.xx.xx.:1521:xxxx", "xxx", "xxx");
stmt = conn.prepareStatement("select * from t_gnl_kisi where ADI like ?");
stmt.setString(1, _ad+"%");
rs = stmt.executeQuery();
while (rs.next()) {
_kisivektor.add(rs.getString("ADI"));
_kisivektor.add(rs.getString("SOYADI"));
_kisivektor.add(rs.getString("ANA_ADI"));
_kisivektor.add(rs.getString("BABA_ADI"));
}
stmt.close();
rs.close();
}
catch (Exception e) {
e.printStackTrace();
}
return _kisivektor;
}
}
You can use the solution discussed here,
http://forums.sun.com/thread.jspa?threadID=5425845&tstart=1 (This is on demand fetching)
This is prefetching
http://forums.sun.com/thread.jspa?threadID=5371696
Finally if you want to get batch of data of 5 rows. You can subclass the Data Model and only read 5 rows and keep connection open. When "Back" or "Forward" buttons are pressed you can scroll the resultset to that many records (you anyway are going to have a twoway scrollable result set)
There is a pattern name for this: Value List Handler which is a specific form of Lazy Loading.