I am using following code for retrieving data from database, but i don't know how to show it in JList
Class.forName("oracle.jdbc.driver.OracleDriver");
Statement stmt = null;
ResultSet rs;
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1/SPL","root","PWD");
stmt=(Statement) conn.createStatement();
rs=stmt.executeQuery(query);
while (rs.next())
{
String stadium = rs.getString("Stadium");
String city = rs.getString("City");
}
But i want to show column data in JList. Can you guys tell me how to do that?
i am using the following code but it is not displaying anything on my frame, can you please tell me where i am wrong? Thanks
String query="SELECT * FROM Location";
DefaultListModel model=new DefaultListModel();
DefaultListModel model1=new DefaultListModel();
try
{ Class.forName("oracle.jdbc.driver.OracleDriver");
Statement stmt = null;
ResultSet rs;
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1/SPL","root","PWD");
stmt=(Statement) conn.createStatement();
rs=stmt.executeQuery(query);
while (rs.next())
{
String stadium = rs.getString("Stadium");
String city = rs.getString("City");
model.addElement(stadium);
model1.addElement(city);
}
JList list=new JList(model);
JList list1=new JList(model1);
f8.add(jpa1); //f8=frame name,jpa1=panel name
jpa1.add(list); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(1);
JScrollPane listScroller = new JScrollPane(list);
}
catch(SQLException e)
{
System.out.println("Message : " + e.getMessage());
}
A JList might be based on a ListModel, so you need to make a ListModel containing your data, and then use this to make your JList. I would make a class Stadium or something, with two String fields, name and city.
public class Stadium {
private String name;
private String city;
public Stadium(String name, String city){...}
//toString()-method to make it display in a meaningful way in the JList
public String toString(){ return name + " - " + city; }
}
and then you can write something like
...
DefaultListModel listModel = new DefaultListModel();
while (rs.next()) {
String name = rs.getString("Stadium");
String city = rs.getString("City");
Stadium stadium = new Stadium(name, city)
listModel.addElement(stadium);
}
JList list = new JList(listModel);
Have not tried to compile and test this code, but hopefully the point is helpful!
Related
I am trying to retrieve images from mysql database using javafx. Images are stored in database using long blob. garbage values appear when doing so . this is the code used to retrieve image from database.
JFXTreeTableColumn<Property,String> propertyImage = new JFXTreeTableColumn<>("Image");
propertyImage.setPrefWidth(100);
propertyImage.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<Property, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<Property, String> param) {
return param.getValue().getValue().propertyImage;
}
});
the property view
Database connection
public class Property extends RecursiveTreeObject<Property>{
StringProperty propertyId;
StringProperty address;
StringProperty state;
StringProperty zipCode;
StringProperty price;
StringProperty bedNum;
StringProperty bathNum;
StringProperty propertyImage;
StringProperty propertyType;
StringProperty propertyStatus;
StringProperty squareFeet;
StringProperty parkingSpot;
StringProperty agent_id;
public Property(){
super();
}
public Property(String propertyId, String address, String state, String zipCode, String price, String bedNum, String bathNum, String propertyImage, String propertyType, String propertyStatus, String squareFeet, String parkingSpot, String agent_id) {
this.propertyId = new SimpleStringProperty(propertyId);
this.address = new SimpleStringProperty(address);
this.state = new SimpleStringProperty(state);
this.zipCode = new SimpleStringProperty(zipCode);
this.price = new SimpleStringProperty(price);
this.bedNum = new SimpleStringProperty(bedNum);
this.bathNum = new SimpleStringProperty(bathNum);
this.propertyImage = new SimpleStringProperty(propertyImage);
this.propertyType = new SimpleStringProperty(propertyType);
this.propertyStatus = new SimpleStringProperty(propertyStatus);
this.squareFeet = new SimpleStringProperty(squareFeet);
this.parkingSpot = new SimpleStringProperty(parkingSpot);
this.agent_id = new SimpleStringProperty(agent_id);
}
}
DB connection
ObservableList<Property> properties = FXCollections.observableArrayList();
Connection connection = DBConnection.getConnection();
try {
PreparedStatement ps = (PreparedStatement)connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
properties.add(new Property(rs.getInt(1)+"",rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getString(9),rs.getString(10),rs.getString(11),rs.getString(12),rs.getString(13)));
}
} catch (SQLException ex) {
Logger.getLogger(SearchSalePropertyController.class.getName()).log(Level.SEVERE, null, ex);
}
Finally, you posted the codes for database access. You are already doing it wrong when you were getting the data from the ResultSet.
while(rs.next()) {
InputStream in = new rs.getBinaryStream(8);
Image image = getImageFromStream(in); // You need to convert this back into a JavaFX Image instance,
// which depends on the original Image, e.g. file format etc.
// It could be as simply as new Image(in) using the JavaFX Image constructor
properties.add(new Property(
rs.getInt(1) + "",
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5),
rs.getString(6),
rs.getString(7),
image,
rs.getString(9),
rs.getString(10),
rs.getString(11),
rs.getString(12),
rs.getString(13)
));
}
Of course, Property.propertyImage should also be changed to ObjectProperty<Image>. Similarly the column should also be changed to JFXTreeTableColumn<Property, Image>.
I am working on a Java assignment that requires pulling languages from a COUNTRY_LANGS_SQL table, then using a loop to display the Country, Population, Median Age, and Language(s) for each country. I'm able to display the 4 Countries, Population, Median Age, but for the life of me I cannot figure out what statement I need to declare in order for it to pull and loop the languages in. I've tried numerous variations with no success, so I'm hoping someone can take a look and point out what I'm doing wrong. Any help would be greatly appreciated.
UPDATE 3: So I'm very close to having this working now with it successfully executing and displaying language column, it's just not displaying the languages of the country (see below)
Name: Canada Population: 34568211 Median Age: 41.5 ID : 1 Language: []
Name: Germany Population: 81147265 Median Age: 45.7 ID : 2 Language: []
Name: South Africa Population: 49601098 Median Age: 25.5 ID : 3 Language: []
Name: Japan Population: 127253075 Median Age: 45.8 ID : 4 Language: []
I also only have one error now in the readLanguages method
"
The method getId() is undefined for the type List
"
/**
* #return list of countries read from the country database
*/
public List<Country> getCountries() {
return countries;
}
private void readLanguages() {
try (
Connection connection = getConnection();
PreparedStatement stmt = connection.prepareStatement(GET_COUNTRY_LANGS_SQL)
) {
for (Country country : countries); {
stmt.setInt(0, countries.getId());
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
int i = 0;
countries.get(i).addLanguage(rs.getString("language"));
rs.close();
}
}}
catch (SQLException e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
It seems to not be pulling the Id's from the Country class, or it's not looping correctly. Any thoughts?
1)CountriesDB.java
package edu.pcc.cis233j.countries;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Read data from the countries database
*
* #author
*/
public class CountriesDB {
private static final String DB_NAME = "Countries";
private static final String DB_URL = "jdbc:jtds:sqlserver://cisdbss.pcc.edu/" + DB_NAME;
private static final String USERNAME = "";
private static final String PASSWORD = "";
private static final String GET_COUNTRIES_SQL = "SELECT * FROM COUNTRY";
private static final String GET_COUNTRY_LANGS_SQL = "SELECT * FROM COUNTRY_LANGUAGE WHERE CountryId = ?";
private List<Country> countries;
/**
* Create a CountriesDB object
* Read from the Countries database and populate the countries list
*/
public CountriesDB() {
countries = readCountries();
}
/**
* Create and return a connection to the database
* #return connection to the countries database
*/
private Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
return connection;
}
/**
* Read country info from the Country table.
* If an error occurs, a stack trace is printed to standard error and an empty list is returned.
* #return the list of countries read
*/
private List<Country> readCountries() {
List<Country> countries = new ArrayList<>();
try (
Connection connection = getConnection();
PreparedStatement stmt = connection.prepareStatement(GET_COUNTRIES_SQL);
ResultSet rs = stmt.executeQuery()
) {
while (rs.next()) {
countries.add(new Country(rs.getInt("Id"),
rs.getString("Name"),
rs.getLong("Population"),
rs.getDouble("MedianAge")));
}
}
catch (SQLException e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
return countries;
}
/**
* #return list of countries read from the country database
*/
public List<Country> getCountries() {
return countries;
}
private void readLanguages() {
try (
Connection connection = getConnection();
PreparedStatement stmt = connection.prepareStatement(GET_COUNTRY_LANGS_SQL)
) {
for (Country country : countries); {
stmt.setInt(0, countries.getId());
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
int i = 0;
countries.get(i).addLanguage(rs.getString("language"));
rs.close();
}
}}
catch (SQLException e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
}
}
2)Country.java
package edu.pcc.cis233j.countries;
import java.util.ArrayList;
import java.util.List;
/**
* A country in the world
* #author Your Name & Cara Tang
*/
public class Country {
private int id;
private String name;
private long population;
private double medianAge;
private List<String> language = new ArrayList<>();
/**
* Create a Country object with the given properties
*/
public Country(int id, String name, long population, double medianAge) {
this.id = id;
this.name = name;
this.population = population;
this.medianAge = medianAge;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public long getPopulation() {
return population;
}
public double getMedianAge() {
return medianAge;
}
public List<String> getLanguage() {
return language;
}
public void addLanguage(String string) {
language.add(string);
}
}
3) CountryMain.java
package edu.pcc.cis233j.countries;
import java.util.List;
/**
* Read from the Country database and print data on the countries
* #author TJ
*/
public class CountryMain {
public static void main(String[] args) {
CountriesDB cdb = new CountriesDB();
List<Country> countries = cdb.getCountries();
for (Country country : countries) {
System.out.println("Name: " + country.getName()
+ " Population: " + country.getPopulation()
+ " Median Age: " + country.getMedianAge()
+ " ID : " + country.getId()
+ " Language: " + country.getLanguage()
);
}
}
}
First, the lines:
countries.add(new Country(rs.getString("Language"),
rs.getString("Language")));
refer to rs before it is declared or populated. Also, they appear to be trying to build a Country from two strings (both the same).
Second,
countries.add(new Language ());
Is crazy because countries has Country objects in it, so you can't just add a Language object, and a new one at that (not from the database).
It's almost as if you didn't write the code yourself and consequently don't understand it...
I think what you need is closer to this:
private void readLanguages() {
try (
Connection connection = getConnection();
PreparedStatement stmt = connection.prepareStatement(GET_COUNTRY_LANGS_SQL)
) {
ResultSet rs = null;
for (Country country : countries); {
stmt.setInt(1, country.getId());
rs = stmt.executeQuery();
while (rs.next()) {
country.setLanguage(rs.getString("Language")); //assumes 1 per country - others are discarded
}
rs.close();
}
}
}
not perfect java - but should give you an idea where you are going wrong.
Other notes:
The easy way to do this (assuming one language per country) would be to join the tables in the SELECT.
You should also close your database connection when finished with it.
I'm not sure that your try (stuff) {statements} syntax is correct.
If there are multiple languages per country, you need that supported in your data structures/classes.
I'm assuming your Country class has getters and setters for the fields.
Note: the question has been updated but I think this is still mostly relevant.
As by design, one Country can have multiple Languages, so your model should look like:
class Country {
private int id;
private String name;
private List<String> language;
//....
}
There are different ways you can construct it, most straight-forward one is something like (in pseudo-code):
List<Country> resultCountries=....;
countryRows = executeGetCountrySql
foreach countryRow in countryRows {
id = row.get("ID");
name = row.get("NAME");
List<String> langs = new ArrayList<();
langRows = executeGetLanguageByCountryIdSql(id);
foreach langRow in langRows {
langs.add(langRow.get("LANGUAGE"));
}
resultCountries.add(new Country(id, name, langs));
}
Some DB iirc does not allow concurrent resultsets. One way you can do is to read all countries first, and loop through each country and get its corresponding languages, and set it back to country.
Another way is to join the country table with country_language, and construct new country / add new language to existing country for each result row.
I'm making a mysql database connector with java to show all the data.
When I run the code, I get an NullPointerException in my getData() function.
here is my code.
public String[][] getData() {
String values[][];
try {
rs = st.executeQuery("SELECT * FROM adresses");
int i = 0;
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
values[i][0] = id;
values[i][1] = name;
values[i][2] = adress;
values[i][3] = catagory;
i++;
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return values;
}
}
When the value of the String values is nothing I get The error. But if I give the String allready a value it says nothing .
public String[][] getData() {
String values[][] = {{"","","",""},
{"","","",""},
{"","","",""},};
try {
rs = st.executeQuery("SELECT * FROM adresses");
int i = 0;
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
values[i][0] = id;
values[i][1] = name;
values[i][2] = adress;
values[i][3] = catagory;
i++;
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return values;
}
}
I want more data than that in my data String. how can I let it automatically do that??
Tnx.
PS.
The function is called in my class FrameGUI and has to change to Object
public class FrameGUI extends JFrame {
public JTable dataHolder;
Mysql mysql = new Mysql();
public String[] columnNames = {
"ID", "Name", "Adress", "Catagory"
};
-> public Object[][] data = mysql.getData();
public FrameGUI() {
init();
mysql.getData();
}
}
You do not initialize String values[][] so it is null. You either need to initialize it first or use a more appropriate datastructure like a List.
You should define a class and use a List (e.g. the ArrayList) instead.
e.g. if you want to call it User -
public class User {
private String id;
private String name;
//...
}
and a list
List<User> users = new ArrayList<User>();
and then instantiate the User class for each row and add the new instance to the list -
User currUser = new User();
users.add(currUser);
//set values from result set
The list can grow automatically when needed and the code is much more readable than using the array.
You get an index out of bounds in the first example because a String[][] (or String Matrix) gets initialized as a zero-length array.
In the second instance, you initialized the array to a size of 3x4 - that works so long as you only get 3 results back.
What you really need is a data structure with a dynamic size. Arrays aren't automatically sized dynamically. Try using a collection implementation like ArrayList or LinkedList or Vector.
Also, instead of saving your values to a String[], try creating a bean class that can hold your result. Create a new instance of it for each result that you get back instead of initializing a new array.
Because you didn't initialized your array, that is why you get NPE. Actually I suggest you to use List for your purposes:
public ArrayList<ArrayList<String>> getData() {
ArrayList<ArrayList<String>> values = new ArrayList<>();
try {
rs = st.executeQuery("SELECT * FROM adresses");
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
ArrayList<String> list = new ArrayList<>();
list.add(id);
list.add(name);
list.add(adress);
list.add(catagory);
values.add(list);
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
The main problem in you code is you are using arrays to save variable number of data. Arrays is fixed sized after they are created so you can't add (or remove) elements to them dynamically.
Instead of using arrays you should use an ArrayList object which have methods to add more elements. Also instead of creating a multidimensional array it looks like a better idea to create a class for the data you get from you database.
So lets first create a Address class:
public class Address {
public String id, name, adress, catagory;
public Address(String id, String name, String adress, String catagory) {
this.id = id;
this.name = name;
this.adress = adress;
this.catagory = catagory;
}
}
Now you can write you code as:
public List<Address> getData() {
List<Address> values = new ArrayList<Address>();
try {
rs = st.executeQuery("SELECT * FROM adresses");
int i = 0;
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
values.add(new Address(id, name, adress, catagory));
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return values;
}
}
The returned list will contain a list of Address objects which have the values from you database. Also, the size of the list is always the same as the content you put into it.
Hi while developing one of my web application i am storing the user information in to an ArrayList based on sql query executed, it contain duplicate objects how to remove duplicate objects in list , i already tried some method but it still not working.
This Is My Code Correct me where i am wrong
public ArrayList loadData() throws ClassNotFoundException, SQLException {
ArrayList userList = new ArrayList();
String url = "";
String dbName = "";
String userName = "";
String password = "";
Connection con = null;
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement ps = null;
try {
String name;
String fatherName;
int Id;
String filePath;
int age;
String address;
String query = "SELECT NAME,FATHERNAME,AGE,ADDRESS,ID,FILEPATH FROM USER_INFORMATION ,USER_PHOTO WHERE ID=USER_ID";
ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
name = rs.getString(1);
fatherName = rs.getString(2);
age = rs.getInt(3);
address = rs.getString(4);
Id = rs.getInt(5);
filePath=rs.getString(6);
/* if(flag)
{
prev=Id;
flag=false;
}
else if(Id==prev)
{
TEMP=TEMP+";"+filePath;
}*/
//PhotoList = PhotoList(Id, con);
UserData list = new UserData();
list.setName(name);
list.setFatherName(fatherName);
list.setAge(age);
list.setAddress(address);
list.setId(Id);
// list.setFilePath(filePath);
userList.add(list);
}
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
ArrayList al = new ArrayList();
HashSet hs = new HashSet();
hs.addAll(userList);
al.clear();
al.addAll(hs);
return al;
}
And My Bean Class contant is
public class UserData {
private String name;
private String fatherName;
private int Id;
//private String filePath;
private int age;
private String address;
public UserData()
{
}
public UserData(String name, String fatherName,int Id, int age,String address)
{
this.name = name;
this.fatherName = fatherName;
this.Id = Id;
//this.filePath=filePath;
this.age=age;
this.address=address;
}
//GETTER AND SETTER..
General Idea: Use Set, not List. But you must override hash and equals of the class.
If you want a Collection of objects that does not have a specific order and you don't want duplicates, it's better for you just to use a Set like for example HashSet, or, if in your set the order is important, the TreeSet.
Just remember to override the hash and equals methods.
if you add this to your bean everything should work:
public int hashCode() {
return (name + fatherName+ Id + filePath + age + address).hashCode();
}
public boolean equals(Object obj) {
return ( hashCode() == obj.hashCode() );
}
Your userdata class does not implement equals or hashcode. This means two instances created with the same values will not be counted as duplicates. This is why the set contains duplicates.
For example
UserData u1 = new UserData("Foo", "bar",1, 1,"baz");
UserData u2 = new UserData("Foo", "bar",1, 1,"baz");
u1 and u2 are not considered equal as they are different objects. Adding an equals and hashcode method should fix this. However even better is adarshr's idea of removing dupes in the SQL.
All duplicates must be removed at an SQL level. Your SQL is suggesting that it could be generating duplicate records.
String query = "SELECT NAME,FATHERNAME,AGE,ADDRESS,ID,FILEPATH FROM USER_INFORMATION ,USER_PHOTO WHERE ID=USER_ID";
What does the clause ID = USER_ID mean? Shouldn't you be passing in that value as an input to your query?
Also, is the column ID a primary key? Otherwise, use a where clause that doesn't generate duplicates.
hi everyone i have this code but don't know why it doesn't work!
//in database class
String query = "SELECT group_name FROM customer ORDER BY group_name";
java.sql.PreparedStatement stm = connection.prepareStatement(query);
rs = stm.executeQuery(query);
while (rs.next()) {
String x = rs.getString("group_name");
System.out.println(x);
}
rs.close();
}
//combo box action
int group = jcombobox.getSelectedIndex();
rg_domain rg = new rg_domain();
rg.setGroup(group);
rg.setPhone_number(phone_no);
dbconnection db = new dbconnection();
db.broadcastmsgservice_sms(rg);
}
//domain class
private String group;
public void setGroup(String group) {
this.group = group;
}
public String getGroup() {
return group;
}
can anyone help me please..
Your question is not very clear, but here's how you fill a combo box with results retrieved from the database:
// Create an array list to be filled with group names
ArrayList<String> groupNames = new ArrayList<String>();
String query = "SELECT group_name FROM customer ORDER BY group_name";
PreparedStatement stm = connection.prepareStatement(query);
ResultSet rs = stm.executeQuery(query);
while (rs.next()) {
String groupName = rs.getString("group_name");
// add group names to the array list
groupNames.add(groupName)
}
rs.close();
// Populate the combo box
DefaultComboBoxModel model = new DefaultComboBoxModel(groupNames.toArray());
comboBox.setModel(model);