I'm having problem with showing database values in my Jtable. I don't know how to use JDataChooser as a searching tool in JTable. I want the process like this, if JDateChooser1 is select to 08-17-2017 and JDateChooser2 is select 09-17-2017
the JTable will only show the values that having that date between 08-17-2017 - 09-17-2017. The format of the Date is (MM-dd-yyyy).
I have this method and as a testing I put the method to a button. I also want to know where I can put this method to be able not using a button. Auto search when I'm done selecting the dates.
sales is my table name in mysql and Date is the column name.
private void Dated() {
try {
String value1, value2;
value1 = jDateChooser1.getDate().toString();
value2 = jDateChooser2.getDate().toString();
String sql = "select * from sales where Date = '" + value1 + "' and '" + value2 + "'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
You are missing some information in your query :
show the values that having that date between 08-17-2017 - 09-17-2017 you have to use between keyword in the query should be select * from sales where Date between date1 and date1 and not =
because you are using prepapred statement don't use concatination of the query and values.
beside Date is reserved keyword in MySQL instead you have to put it between two ``
Your code should look like :
Date value1 = jDateChooser1.getDate();
Date value2 = jDateChooser2.getDate();
String sql = "select * from sales where `Date` between ? and ?";
pst = conn.prepareStatement(sql);
pst.setDate(1, value1);
pst.setDate(2, value2);
rs = pst.executeQuery();
Related
I want to sort sql results with a date that i get from jDateChooser and display all the returned results. This is what i have done so far. So far I have only managed to get 1 result even if i looped the sorted sql results.
public void MonthlyTotalExpenses_Report(){
String typeOfReport = (String) report_type.getSelectedItem();
String reportDate = ((JTextField)report_date.getDateEditor().getUiComponent()).getText();
db databaseCon = new db();
Connection dbconnect = db.dbconnect();
if(typeOfReport == "Total expenses"){
String selectQuery = "select name,type,sum(amount),date_payed from expenses order by ? DESC";
try{
Connection con = databaseCon.dbconnect();
ResultSet rs = null;
PreparedStatement pst = null;
pst = con.prepareStatement(selectQuery);
pst.setString(1,reportDate);
rs = pst.executeQuery();
List<String> results = new ArrayList<String>();
while(rs.next()) {
results.add(rs.getString(1));
}
for(String result : results) {
System.out.println(result);
}
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I want sort the results like this (for example -> 2017-01-01 to the date user select with jDateChooser) and print all the records available within that period. I just figured the sql query i wrote is wrong. It only prints the 1st value of the name column in the database. Help me to figure out how to sort according what i have mentioned above and print all the results that returned.
You might want to set the date in the where condition in your query.
select name,type,sum(amount),date_payed from expenses where date_payed = ? order by 4 DESC
Consider obtaining Date from String.
String reportDate = ((JTextField)report_date.getDateEditor().getUiComponent()).getText(); // "2017-01-01"
DateFormat format = new SimpleDateFormat("YYYY-MM-DD", Locale.ENGLISH);
Date date = format.parse(reportDate);
Then set your param with
pst.setDate(1,reportDate);
I am developing simple swing application to get some information from the database.
Two of the field in database table called Used_PR & Create_PR.
As follows,
Data structure is like mention below.
PR-L-Machine-Date-Shift
Then I want to retrieve data by PR.
Here is my interface to insert search details
Date choose from date JDateChooser.
I used LIKE clause to get data from the db, but it does not work.
Here is the MYSQL query statement.
String prlQuery = "SELECT * FROM final_report WHERE used_PR LIKE '?%' OR create_PR LIKE '?%'";
try {
Date chooseDate = new Date(dateChooser.getDate().getTime());
String parameter = "PR-L-" + selectMachine.getSelectedItem() + "-" + chooseDate;
pst = connect.dbConnection().prepareStatement(prlQuery);
pst.setString(1, parameter);
pst.setString(2, parameter);
But seems it is not working. Can somebody help me with this code structure.
You must pass the % in the parameters
your query must look like
String prlQuery = "SELECT * FROM final_report WHERE used_PR LIKE ? OR create_PR LIKE ?";
try {
Date chooseDate = new Date(dateChooser.getDate().getTime());
String parameter = "PR-L-" + selectMachine.getSelectedItem() + "-" + chooseDate;
pst = connect.dbConnection().prepareStatement(prlQuery);
pst.setString(1, parameter+"%");
pst.setString(2, parameter+"%");
How do you go about putting records into a jTextField when an item is selected from a jComboBox? For example, I'm making an airline reservation system and I have a combo box with the available flights. Below it are text fields with designated info like departure date, departure time, arrival date, etc. How do I make it so that when the user selects an item from the the combo box, (ex. flight name is CX9005) the corresponding info from the same row is shown in the text fields? (ex. departure date is November 12 2015)
EDIT:
So I tried doing that with the ff. code, but I got a syntax error and a ResultSet not open error.
private void combo_FlightItemStateChanged(java.awt.event.ItemEvent evt) {
try{
flightID = combo_Flight.getSelectedItem().toString();
String flightName = combo_Flight.getSelectedItem().toString();
String query = "Select * from ACCOUNTS where flightName = \'"+flightName+"\';";
rs = stmt.executeQuery(query);
}
catch(SQLException err){
JOptionPane.showMessageDialog(UserModule.this, err.getMessage());
}
}
Also, I use this function to connect to my database if that matters.
public void DoConnect() {
try{
String host = "jdbc:derby://localhost:1527/UserAccounts";
String uName = "Bryan";
String uPass = "Cruz";
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM ACCOUNTS";
rs = stmt.executeQuery(sql);
}catch(SQLException err){
JOptionPane.showMessageDialog(Connect.this, err.getMessage());
}
}
Also, I might not have been too clear with my original post. I want to make it so that when the user selects a flight from the combo box, all of that flight's details show up in the appropriate text fields. (ex. departure date, departure time, destination, etc.) I'm confused on how to make this work so help would be much appreciated!
You get the text from the comboBox using getSelectedItem() or getSelectedValue().
You can then create a MySQL query like:
String flightName = yourComboBox.getSelectedItem().toString();
String query= "Select * from yourTable where flightName = \'"+flightName+"\';";
Then you can execute this query using executeQuery()
Now for the part with setting results in all testfields
First store the result in a ResultSet object
rs = stmt.executeQuery(query);
rs.next();
Now you have the result in object rs
Use rs.getString(columnNumber) to get records from the result
Eg.
String departureDate = rs.getString(4);
// assuming the column number is 4
Do this to get all required strings.
And set them in respected columns using setText() method
flightID = combo_Flight.getSelectedItem().toString();
String flightName = combo_Flight.getSelectedItem().toString();
What is the point of the above two statements? You can't get two values from the same combo box. Either you get the flightID or the flighName.
String query = "Select * from ACCOUNTS where flightName = \'"+flightName+"\';";
but I got a syntax error
Don't try to build the SQL string manually. Instead you can use a PreparedStatement. It will make sure the proper delimiters are used so you just concentrate on the SQL statement:
String flightName = combo_Flight.getSelectedItem().toString();
String query = "Select * from ACCOUNTS where flightName = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString( 1, flightName );
ResultSet rs = stmt.executeQuery();
So you will need access to the Connection object you established in the doConnect() method. Note, method names should NOT start with an upper case character.
Also, I believe the standard for database column names is to capitalize the words of the column, so you should be using "FlightName" not "flightName" as the column name.
I want to search column called name in my work table by searching date. Other columns are id(primary key) and mydate. I can't find what is wrong with my code. I'm using jdbc class for db connection.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(jDateChooser1.getDate());
String time1 = dateSpinner1.getValue().toString().split(" ")[3];
date1 = date1 + " " + time1;
try {
ResultSet rs =db.getData("SELECT * FROM work WHERE mydate = '"+date1+"'");
while (rs.next()) {
String name = rs.getString("name");
System.out.println(name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
date is the name of a function in MySQL. You'll need to wrap it in ` characters:
ResultSet rs =db.getData("SELECT * FROM work WHERE `date` = '"+date1+"'");
One possible error may be that in database hours minutes and seconds are not 0:0:0 and from datechooser you are getting these fields as 0 : 0
Could you pass the date1 as date in the statement (as parameter)?
"SELECT * FROM work WHERE date = ?" and pass parameter as date
I have 3 comboboxes in Java which are ;
'departurecities={city1,city2,city3}
destinationcities={city1,city2,city3}
date={1,2,3,4,5,6...}
I want to define a variable for the date because I don't know, what user will bus date, so I need a variable for SQL query.
I want to query like that:
sql=select busid from buses where dep='city1'and des='city2' and
datebus=(????variable????);
how can I define it ???
Please help me ..
Thanks in advance
PreparedStatement
In case you want to pass a variable to your SQL statement, I would recommend a PreparedStatement. See Oracle Tutorial.
You can use setInt in order to pass an integer, setString to pass a String etc.
Here is the API.
Here is an example:
String result = null;
String query = "select busid from buses where dep='city1'and des='city2' and datebus=?";
try {
PreparedStatement preps = con.prepareStatement(query);
preps.setInt(1, Integer.parseInt((String) date.getSelectedItem()));
preps.execute();
rs = preps.getResultSet();
if (rs.next()) {
result = rs.getString(...);
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
I assume that datebus is declared as an integer in your database table.
You can use a String type for a constant like '2012-12-31 12:00 am', or, Date or GregorianCalendar if you want to manipulate days/date differences in Java.
In SQL, you can convert string or character values into SQL's internal date format with the to_date() function:
SQL examples:
to_date('29-Oct-09', 'DD-Mon-YY')
to_date('10/29/09', 'MM/DD/YY')
to_date('120109', 'MMDDYY')
So, if you wanted to create a SQL command from Java:
String date = "12/31/2012";
String dep = "city1";
String des = "city2";
String SQL = "INSERT INTO buses VALUES(" + dep + "," + des + ",to_date(" + date + ",'MM/DD/YYYY'));";