so what I am trying to do is update a JLabel that is going to represent the number of files that are stored in my database.
I will use JDBC to communicate my Java application with my database (Oracle) and pass a SQL statement to my database to return output in this case it will be: SELECT COUNT(File_ID) FROM Files; which would give an output of say 50.
So now I would like to update my Jlabel I have to display the output, in this case it would read 50.
I know how to update a JTable with the results from a database like so:
try {
String query = "SQL STATEMENT GOES HERE";
pat = conn.prepareStatement(query);
rs = pat.executeQuery();
myTable.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e) {
e.printStackTrace();
}
However I have never used output to update a Jlabel, if you have any suggestions or advice on how to achieve this it would be greatly appreciated. Thanks!
Just use label.setText()
Edited: I didn't find an equivalent TextModel for jlabel (it exits for other components such as JTextField). Is it critical for you to go through a "Model" or is it good enough to setText("50")?
To extract the count do something like:
int count=0;
pat = conn.prepareStatement("SELECT COUNT ..."); // complete as required
ResultSet rs=pat.executeQuery();// assuming it's "SELECT COUNT..."
if(rs.next())
count=rs.getInt(1);
Related
Cheers everyone, beginner here!.
I'm currently working on a Java application to keep track of the inventory in our warehouse. It's all on localhost until it's finished. I've created two tables in MySQL database: one table shows the article code, location and quantity (VOORRAADSYSTEEM); the other table shows article code and description (STAMDATA).
In my GUI, I've got a JTable which loads data from VOORRAADSYSTEEM, and on mouseclickevent (getSelectedRow) shows the data in the corresponding JTextFields (so far so good). The only field not showing is the description field (which should be read from the STAMDATA table).
I've tried creating a method for this specific part of the program. The method runs a query to the second table using a inner join to the first table. Here's the code below.
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(2, sql);
descriptionTxt.setText(rs.getString(sql));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
At this moment I'm not exactly sure how to approach this problem. I'm also going to try using foreign keys. Any help would be appreciated.
There are better ways to handle what you want to do. For instance you could get all the information you need with one query by joining the table on a common column (ARTICLENUMBER and ARTICLECODE) and then display it.
Right now it looks/sounds like you might be trying to get all the information with two queries.
However, there are some errors with your load description method:
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
ResultSet results = conn.createStatment().executeQuery(sql);
if(results.next()) //make sure something was returned to avoid null pointer exception
descriptionTxt.setText(rs.getString("DESCRIPTION"));
else
JOptionPane.showMessageDialog(null, "no results returned");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
This should work a little better for you.
Kindly help me to solve this problem, also tell me how to display data on the table by using condition on comboBox. Following is the code and Output. Please help me, as I have to show this to my instructor tomorrow.
public ArrayList<User> userList() {
ArrayList<User> usersList = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://localhost:1433;databasename=DB_Project;user=User;Password=password";
Connection con= DriverManager.getConnection(url);
String query = "SELECT * FROM tbl_Income";
Statement st=con.createStatement();
ResultSet rs= st.executeQuery(query);
User user;
while(rs.next()){
user= new User(rs.getInt("Amout"),rs.getString("Date"),rs.getString("Source"));
usersList.add(user);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
return usersList;
}
public void show_user() {
ArrayList<User> list = userList();
DefaultTableModel model = (DefaultTableModel)Income_Table.getModel();
Object[] row =new Object[3];
for(int i=0;i<list.size();i++){
row[0]=list.get(i).getAmout();
row[1]=list.get(i).getDate();
row[2]=list.get(i).getSource();
model.addRow(row);
}
}
//**********tbl_Expense
public ArrayList<User_E> userList_E() {
ArrayList<User_E> UsersList_E = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String eurl="jdbc:sqlserver://localhost:1433;databasename=DB_Project;user=User;Password=password";
Connection con= DriverManager.getConnection(eurl);
String query_E = "SELECT * FROM tbl_Expense";
Statement stt=con.createStatement();
ResultSet rst= stt.executeQuery(query_E);
User_E user_e;
while(rst.next()){
user_e = new User_E(rst.getString("ExpenseDetail"),rst.getString("Category"),rst.getString("Date"),rst.getInt("Amount"));
UsersList_E.add(user_e);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
return UsersList_E;
}
public void showuser_E(){
ArrayList<User_E> list_E = userList_E();
DefaultTableModel model_e = (DefaultTableModel)Expense_Table.getModel();
Object[] row_e =new Object[4];
for(int i=0;i<list_E.size();i++){
row_e[0]=list_E.get(i).getAmount();
row_e[1]=list_E.get(i).getDate();
row_e[2]=list_E.get(i).getCategory();
row_e[3]=list_E.get(i).getExpenseDetail();
model_e.addRow(row_e);
}
}
This is the Output, getting 0 instead of original data
I cannot tell what the issue by looking at the code posted. But, the application's database access, querying and showing the data in the GUI need to be structured something like this:
1. Access database and get connection:
Get connection object for the database DB_Project (there is no need to create connection objects twice).
2. Query 1:
Create statement
Query the tbl_Income table and populate the "userList"
Close the statement (this also closes the corresponding result set)
3. Query 2:
Create statement
Query the tbl_Expense table and populate the "userList_E"
Close the statement
4. Close connection (this is optional and depends on application requirement).
5. Display GUI using the queried data:
Show user income JTable using the "userList"
Show user expense JTable using the "userList_E"
NOTES:
Place some debug or log statements in the Java code and verify if there is any data in the tables being queried and also what kind of data it is. Querying the database tables directly and interactively or from the command prompt also helps. Also, after populating the list collections print the lists onto the console using System.out.prinltln() statements to verify if the data is populated to them properly.
How to display based on combo box selection:
Here is the link to Java tutorials on using Swing JComboBox - see the section "Handling Events on a Combo Box".
There are different ways one can build the code to acheive this functionality.
By directly querying the database table using the data selected from
the combo box, or
By filtering the data from the "list" data already queried and populated to it. This option requires the queried data from the database tables be stored in instance variables.
Again, it depends upon the application requirement. In case the database table data is not changing then option 2 is the correct method, otherwise query the database table directly.
One hideous thing: nothing is closed (connection, statement, result set).
Try-with-resources may help here, to automatically close those, even on return, break, raised exception.
public ArrayList<User_E> userList_E() {
ArrayList<User_E> usersList_E = new ArrayList<>();
String eurl = "jdbc:sqlserver://localhost:1433;databasename=DB_Project;"
+ "user=User;Password=password";
String query_E = "SELECT * FROM tbl_Expense";
try (Connection con = DriverManager.getConnection(eurl);
Statement stt = con.createStatement();
ResultSet rst= stt.executeQuery(query_E)) {
while(rst.next()){
User user_e = new User_E(rst.getString("ExpenseDetail"),
rst.getString("Category"),
rst.getString("Date"),
rst.getInt("Amount"));
usersList_E.add(user_e);
}
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
return usersList_E;
}
Class.forName on the driver class is since years no longer required.
For the error: I can only assume that the application is running out of free connections.
I have a problem with this for a while. Importing data from TEXT field into textArea make no problem for me (even if it's longer than String), but I have no idea how to make it work opposite way. (Using sqlite)
My code to get data from db:
Statement myStmt = con.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT * from test");
while(myRs.next())
{
if(myRs.getInt("Id_przepisu") == przepis.getId_przepisu() )
{
textArea.setText(myRs.getString("text"));
}
}
myStmt.close();
myRs.close();
code to save data in db
insert = con.prepareStatement
( "INSERT INTO test (Id_przepisu, text) VALUES ('"+przepis.getId_przepisu()+"','"+
textArea.getText()+"')");
insert.executeUpdate();
You might find a good answer and workaround for you problem here: https://stackoverflow.com/a/17785119/575643
In short, if is bigger than the TEXT type you would need to split it manually. Search for substring, it would help.
below is code is a code i wrote to get the value of 'monthly Depreciation' when i select the row on my j Table by either mouse-clicked or key-pressed. but it only selects the first value for 'monthly depreciation' when i click on the rows or key-press.the problem i know is coming from the where statement but can't seem to get around it.
if(evt.getKeyCode()==KeyEvent.VK_DOWN || evt.getKeyCode()==KeyEvent.VK_UP)
{
try{
int row =dep_report.getSelectedRow();
String Table_click=(dep_report.getModel().getValueAt(row, 0).toString());
String sql ="select Date_Acquired 'Date Acquired',Serial_Number 'Serial Number',"
+ " Description 'Description',Cost_Of_Acquisition 'Cost Of Acquisition',"
+ "Monthly_Depreciation 'Monthly Depreciation',Accumulated_Depreciation 'Accumulated Depreciation',Net_Book_Value 'Net Book Value'"
+ ",asset_update.Branch_Area 'Branch Area',Depts_name 'Department Name' ,User 'User',"
+ "Status 'Status' from items,asset_update where items.items_No = asset_update.items_No &&'"+Table_click+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()){
String add1 = rs.getString("Monthly Depreciation");
MonthlyDep.setText(add1);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
I would really appreciate the help thank you.
In your sql
where items.items_No = asset_update.items_No &&'"+Table_click+"'";
&& wont work for sql and you might need
where items.items_No = asset_update.items_No and items.someThing= '"+Table_click+"'";
Please use Java naming conventions and give proper names to things Table_click is a horrible variable name.
But can you describe what is in your table model in the 1st column of the selected row?
You seem to append that to your query and if it does not contain a valid SQL part, this will not work well with your statement. In a where clause you usually check a column against a value. I doubt that your table model has this written there, more likely you just have the value in your table model at this position.
Also make sure to properly use prepared statements. Never put the values directly in the SQL string you create or you create the perfect entry point for SQL injection. Assign the values instead once you have created the statement with something like this: pst.setString(1, Table_click);
i have one problem with database in java
my code is ( its only one small part of my project)
public void Read_from_DB(int exhibition_id){
Statement stmt = null;
Connection connect = null;
try {
connect=MYConnection.new_connection();
stmt = connect.createStatement();
QuestionCatalog.get_QuestionCatalog_instance().setShow_quest(new ArrayList<Question>());
String sql = "SELECT * FROM question WHERE Selection=0 AND exhibition_id="+exhibition_id;
//System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
System.out.println("!");
System.out.println("->"+rs.getFetchSize());
while(rs.next()){
Question jd=new Question();
System.out.println("!!!");
jd.setQuestion_id(rs.getInt("Question_id"));
jd.setQuestion(rs.getString("Question"));
jd.setQuestion(rs.getString(exhibition_id));
jd.getOption_2().setContent(rs.getString("Content2"));
QuestionCatalog.get_QuestionCatalog_instance().getShow_quest().add(jd);
System.out.println("size"+QuestionCatalog.get_QuestionCatalog_instance().getShow_quest().size());
MYConnection.close_connection(stmt, connect);
}
}catch (Exception e) {
}
}
when i execute this code it dosent work
my database table name is "question"
but when i change the name in this query to "Question" , don't get any error
then i think it doesn't execute my query,my main is
public static void main(String[] args) {
DB_question d=new DB_question();
d.Read_from_DB(1);
}
and "MYConnection.new_connection();" in part on of code return a connection,( i test it in another class it work)
the result in console is :
SELECT * FROM Question WHERE Selection=0 AND exhibition_id=1
!
->0
it haven't show "!!!"that is result of "System.out.println("!!!");"
then i think it doesnt work :|
thanks
p.s the picture of my db
picture
What I understand from your question is improper output on case sensitive names on table names or column names. Am I right?
As far as I know, reserved words like SELECT, FROM, etc. are case in-sensitive in all OS's. And all other user defined object names are case-sensitive, in *ix OS environment. But not in in Windows OS environment.
But all RDBMS configurations should be allowing case-insensitivity for cross platform deployment. This is the reason why your change from question to Question did not throw an error.
And regarding the outcome of your query:
I fear you have tested your query on different databases or servers. They might not have same data and hence always not entering into while( rs.... loop.
Change your code as below and see what the output is:
ResultSet rs = stmt.executeQuery(sql);
System.out.println("!");
System.out.println("->"+rs.getFetchSize());
rs.beforeFirst();
rs.last();
int rowCount = rs.getRow();
System.out.println( "---> rowCount: " + rowCount );
rs.beforeFirst();
while( ...
Also refer to:
DBMS Identifiers and Case Sensitivity - MysQL