my problems is that i dont know how to make a list (Jlist from NetBeans) with some data from my derby db
EX:
I have a form that saves the id,name,phone and email from a "client", and i want to show all the names from my previously registered clients in a list, the problem is that i need to convert the varchar data into a listmodel. How can i do that? I tried this, but didn't work:
while (rs.next()){
int id_col = rs.getInt("clientID");
String name = rs.getString("clientName");
client_listClients.setText(name);
}
It says that "couldn't find symbol" for .setText
EDIT using DefaultListModel
WORKING RESULT!
public void DoConnect( ) {
DefaultListModel model = new DefaultListModel();
client_listClients.setModel(model);
try {
String host = "jdbc:derby://localhost:1527/ANAIA_DB";
String uName = "*****";
String uPass = "*****";
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement();
String sql = "SELECT * FROM APP.CLIENT";
rs = stmt.executeQuery(sql);
while (rs.next()){
int id_col = rs.getInt("clientID");
String name = rs.getString("clientName");
model.addElement(name);
}
} catch (SQLException err) {
JOptionPane.showMessageDialog(main.this, err.getMessage());
}
}
Thx aloooot #peeskillet
"It says that "couldant find symbol" for .setText"
JList has no method setText(). When in doubt, read the docs
Instead, you'll want to use a ListModel. If you don't want to create your own, you can use the provided DefaultListModel implementation. There you have the method addElement.
You first need to declare your your list with the model.
DefaultListModel model = new DefaultListModel();
JList client_listClients = new JList(model);
Then you can use the method addElement, which will automatically update the UI after all additions are made. No need to do anything with the list.
while (rs.next()){
String name = rs.getString("clientName");
model.addElement(name);
}
You can see more at How to use Lists, and focus on the section Creating a Model
Related
I'm developing a cinema Database, using PostgreSQL, and implementing it graphically with Java.
Everything is working fine but this: i have a PreparedStatement used in a method written like this:
getFilmByGenrePS = connection.prepareStatement("SELECT * FROM Film WHERE genre = ?");
public List<Film> getFilmByGenre(String Genre) throws SQLException{
getFilmByGenrePS.setString(1, Genre);
ResultSet rs = getFilmByGenrePS.executeQuery();
List<Film> list = new ArrayList<Film>();
while(rs.next()) {
Film f = new Film(rs.getInt("CodF"));
f.setFilmName(rs.getString("Name"));
f.setGenreFilm(rs.getString(3));
f.setLenght(rs.getInt("lenght"));
f.setCast(rs.getString("castfilm"));
f.setDirector(rs.getString("director"));
f.setDate(rs.getDate("date"));
f.setDateout(rs.getDate("dateout"));
list.add(f);
}
rs.close();
return list;
}
Genre is an ENUM TYPE in pgadmin.
Then, in my GUI, i have a Combobox with every Genre listed in it, written like this:
JComboBox GenrecomboBox2 = new JComboBox();
GenrecomboBox2.setBounds(60, 485, 150, 27);
panelViewFilm.add(GenrecomboBox2);
GenrecomboBox2.addItem("Animation");
GenrecomboBox2.addItem("Adventure");
GenrecomboBox2.addItem("Action");
Then, I have a button that, when pressed, takes my selected Genre from the Combobox, and passes it to the GetAllFilmByGenre() method as a parameter, so it can substitute it to the '?' in the PreparedStatement.
JButton btnViewFilmGenre = new JButton( new AbstractAction("Vai") {
#Override
public void actionPerformed( ActionEvent e ) {
String genreFilm = (String) GenrecomboBox.getSelectedItem();
DefaultTableModel model = (DefaultTableModel) tableViewFilm.getModel();
model.setRowCount(0);
try {
List<Film> listfilm = new ArrayList<>();
listfilm = filmdao.getFilmByGenre(genreFilm);
System.out.println(listfilm);
for (Film f : listfilm) {
Object[] o = new Object[8];
o[0] = f.getCodF();
o[1] = f.getFilmName();
o[2] = f.getDirector();
o[3] = f.getGenreFilm();
o[4] = f.getCast();
o[5] = f.getLenght();
o[6] = f.getDate();
o[7] = f.getDateEnd();
((DefaultTableModel) tableViewFilm.getModel()).addRow(o);
}
} catch (SQLException e1) {
System.out.println("");
}
}
});
Thing is, this does absolutely nothing. Overall, I think the code works. I used exact same versions of these code by retrieving different parameters and it works flawlessly.
Worth noting: the problem is that it doesn't populate my list at all. I tried to print the list after creating it, and nothing shows up. I get no SQLExceptions or anything.
I think the problem is the parameter i pass. Like, the query "SELECT * FROM FILM WHERE Genre = ?" (with ? substituted with, for example, 'Action') gets executed, but simply doesn't find anything that matches, thus giving me nothing. But if I write "SELECT * FROM FILM WHERE Genre = 'Action'", the query works.
I don't know how to resolve this. I used this exact Combobox for inserting values in my Database and it works. I tried for hours. I'm sure I'm slipping on something stupid, maybe the interaction between the String I use as a parameter in substitution of the '?' is wrong on syntax, but i can't get it. Any help?
Attempting to push this object that I'm building my while loop into a list array. I can't exactly figure out what I'm doing wrong. Can some one please explain first, what the best syntax is and the best way to pull out this information to push it to a list array. so later I can access the list array by getting the information out of it.
public void getTableConnection() throws ClassNotFoundException,
SQLException {
List<Car>cars = new ArrayList<Car>();
Car car = new Car();
try {
Table table = new Table();
table.getTableConnection();
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/carrentalsystem";
String username = "root";
String password = "javatest";
String query = "select * from cardetails";
Connection conn = DriverManager.getConnection(url, username,
password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
car.setId(rs.getInt("id"));
car.setYear(rs.getString("Year"));
car.setMake(rs.getString("Make"));
car.setModel(rs.getString("Model"));
car.setColor(rs.getString("Color"));
car.setAvailable(rs.getString("Availability"));
String renting;
car.add()
}
return cars;
}catch(Exception e) {
}finally{
}
}
I had to change that line to cars.add(car)
At the first place you didn't add car to cars.You can't change the value of the returned ArrayList (cars) in the finally block if it is already returned. So don't return from try.
In my project, a have a bunch of labels for some purpose. Since I am able to move them on stackpane using drag, I want to be able to save their new location in my app. So I was thinking about database, with columns for X and Y position, name of the label and its text.
However, since i want to use quite a lot of labels, I didn't want to code load of labels from database one by one, so I used this:
private void button_load(ActionEvent event) {
try{
String host = "jdbc:sqlite:C://app/app.sqlite";
Connection con = DriverManager.getConnection(host);
PreparedStatement pst = null;
String SQL = "select * from labels";
pst=con.prepareStatement(SQL);
ResultSet rs=pst.executeQuery();
while(rs.next()){
String name=rs.getString("Name");
Double Y=rs.getDouble("Y");
Double X=rs.getDouble("X");
String Text=rs.getString("Text");
name.setLayoutX(X);
name.setLayoutX(Y);
name.setText(Text);
}}
catch (SQLException ex)
{ Logger.getLogger(app.class.getName()).log(Level.SEVERE, null, ex);}}
Obvious problem is, that I am not allowed to use content of the string ("name" in this case) for further use as label ("string cannot be converted to label"). I have been searching for some solution, but haven't found any.
So I would like to ask, is there a way, how to convert string to label or any other way that would help be in this situation?
Thanks
You need to create a new Label for each record and add it to your pane:
private Pane pane = ... // Or group or some other form of a container
private void button_load(ActionEvent event) {
try{
String host = "jdbc:sqlite:C://app/app.sqlite";
Connection con = DriverManager.getConnection(host);
PreparedStatement pst = null;
String SQL = "select * from labels";
pst=con.prepareStatement(SQL);
ResultSet rs=pst.executeQuery();
while(rs.next()){
Label label = new Label();
String name=rs.getString("Name");
Double Y=rs.getDouble("Y");
Double X=rs.getDouble("X");
String Text=rs.getString("Text");
label.setLayoutX(X);
label.setLayoutX(Y);
label.setText(Text);
label.setId(name);
pane.getChildren().add(label);
}
} catch (SQLException ex){
Logger.getLogger(app.class.getName()).log(Level.SEVERE, null, ex);
}
}
I am not sure what you store under name, my guess is that it could be the id of the node.
I wanted to create an update button for a dropdown list that gets the data from the database in the netbeans. Tried this method below but couldn't get it to work. Any suggestions? Thanks alot.
public class ViewProduct extends javax.swing.JFrame {
ResultSet rs;
PreparedStatement pst;
Connection conn;
final void FillList(){
try{
//establish connection to table
String url = "jdbc:derby://localhost:1527/ProductInformation";
String username = "admin1";
String password = "admin1";
Connection conn = DriverManager.getConnection(url,username,password);
Statement stat = conn.createStatement();
// get data from table in sql database
String Query = "SELECT * FROM VIEWPRODUCT";
ResultSet rs = stat.executeQuery(Query);
//
DefaultListModel DLM = new DefaultListModel();
while(rs.next()){
JList list = new JList();
JComboBox ProductID_dropdown = new JComboBox();
DefaultComboBoxModel listModel = new DefaultComboBoxModel();
list.setModel(listModel);
ProductID_dropdown.setModel(listModel);
}
}catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex.toString());
}
There are several things not right or missing in your code. For instance you have no GUI.
And as I dont know the exact structure of your project or your database, I have to improvise and give you a pseudo-code approach.
You will have to change and configure several things I am showing here.
First, create a JComboBox outside of your method and add it to a container like JPanel:
JPanel pane = new JPanel();
JComboBox productID_dropdown = new JComboBox();
JButton btn_updateViewProducts = new JButton("Update Results");
Here the Button for updating your results is added, it contains an ActionListener, that "listens" to when someone is clicking on the button.
Usually you want to retrieve a ResultSet and put its contents into variables, like in this example:
// ActionListener for the button
btn_updateViewProducts.add(new ActionListener{
#Override
// When the button is clicked...
public void actionPerformed(ActionEvent arg0) {
// ... get the results out of your database (here it's an example database!
// Configure for your own one)
ResultSet rs = stat.executeQuery(Query);
while(rs.next()){
// "de-construct" every result of the ResultList into variables
String query = "select COF_NAME, SUP_ID, PRICE, " + "SALES, TOTAL " + "from " + dbName + ".COFFEES";
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
// Put items into JComboBox
productID_dropdown.addItem(coffeeName);
}
}
});
// Add the now filled JComboBox to the pane
pane.add(productID_dropdown);
Other issues you should think about:
GUI is missing
the method FillList is final, which seems unusual, any reason behind this? final in a method means, that it cant be overridden by subclasses, it this needed here?
FillList is a method and should be written with a small letter at the start due to coding convention, the same goes for ProductID_dropdown (coding convention)
most of the time it's quite okay to use short variables like rs for a ResultSet, but if your projects get bigger, it gets harder to keep all those variables in mind. Better: make them tell you, what they are. Instead of rs -> resultSetViewProduct or similar.
PreparedStatement pst is never used
I hope this helps. :)
The title is the error I'm getting, when I click load my program freezes. I assume it's because I'm doing a statement inside a statement, but from what I see it's the only solution to my issue. By loading, I want to just repopulate the list of patients, but to do so I need to do their conditions also. The code works, the bottom method is what I'm trying to fix. I think the issue is that I have 2 statements open but I am not sure.
load:
public void DatabaseLoad()
{
try
{
String Name = "Wayne";
String Pass= "Wayne";
String Host = "jdbc:derby://localhost:1527/Patients";
Connection con = DriverManager.getConnection( Host,Name, Pass);
PatientList.clear();
Statement stmt8 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL8 = "SELECT * FROM PATIENTS";
ResultSet rs8 = stmt8.executeQuery( SQL8 );
ArrayList<PatientCondition> PatientConditions1 = new ArrayList();
while(rs8.next())
{
PatientConditions1 = LoadPatientConditions();
}
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM PATIENTS";
ResultSet rs = stmt.executeQuery( SQL );
while(rs.next())
{
int id = (rs.getInt("ID"));
String name = (rs.getString("NAME"));
int age = (rs.getInt("AGE"));
String address = (rs.getString("ADDRESS"));
String sex = (rs.getString("SEX"));
String phone = (rs.getString("PHONE"));
Patient p = new Patient(id, name, age, address, sex, phone,
PatientConditions1);
PatientList.add(p);
}
UpdateTable();
UpdateAllViews();
DefaultListModel PatientListModel = new DefaultListModel();
for (Patient s : PatientList) {
PatientListModel.addElement(s.getAccountNumber() + "-" + s.getName());
}
PatientJList.setModel(PatientListModel);
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
}
This is the method that returns the ArrayList of patient conditions
public ArrayList LoadPatientConditions()
{
ArrayList<PatientCondition> PatientConditionsTemp = new ArrayList();
try
{
String Name = "Wayne";
String Pass= "Wayne";
String Host = "jdbc:derby://localhost:1527/Patients";
Connection con = DriverManager.getConnection( Host,Name, Pass);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM PATIENTCONDITIONS";
ResultSet rs5 = stmt.executeQuery( SQL );
int e = 0;
while(rs5.next())
{
e++;
String ConName = (rs5.getString("CONDITION"));
PatientCondition k = new PatientCondition(e,ConName);
PatientConditionsTemp.add(k);
}
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
return PatientConditionsTemp;
}
I had a similar problem.
I was connecting to derby db hosted on local server.
I created 2 simultaneous connections:
With squirrel
With ij tool
When a connection makes a modification on a table, it first gets a lock for the particular table.
This lock is released by the connection only after committing the transaction.
Thus if the second connection tries to read/write the same table, a msg prompts saying:
ERROR 40XL1: A lock could not be obtained within the time requested
To fix this, the connection which modified the table has to commit its transaction.
Hope this helps !
Here is a good place to start: http://wiki.apache.org/db-derby/LockDebugging
You need to close your statement and result set as well so that when you restart your program they won't be open. Add stmt.close(); and rs.close(); at the end of your lines of code within the try and catch statement.
Why could you not use the same connection object to do both the queries?
Like pass that connection object to the LoadPatientConditions() as a parameter and use it there.