account_id current_balance opening_date
1 100 2012-03-01
2 100 2012-4-01
3 100 2013-03-1
now when I am running query in sql work bench it's fine
select count(acc.account_id)
from daily_account acc
where acc.opening_date < '2013-03-01'
but when I am running this in NetBeans it is not giving proper output.
select count(acc.account_id)
from daily_account acc
where acc.opening_date < '"+ new Date((Integer.parseInt(FromYearComboBox.getSelectedItem().toString())-1900),FromMonthComboBox.getSelectedIndex(),Integer.parseInt(FromDateComboBox.getSelectedItem().toString()))).toString()
can any one help me why is this happening?
Edit :
rs = st.executeQuery("select count(acc.account_id) from daily_account
acc where acc.opening_date < '"+ new
Date((Integer.parseInt(FromYearComboBox.getSelectedItem().toString())-1900),FromMonthComboBox.getSelectedIndex(),(Integer.parseInt(FromDateComboBox.getSelectedItem().toString()))).toString()+"';");
rs.next();
tabledata[0][2]=rs.getString(1);
Edit ::
It is giving me wrong answer ...it is counting all the account id...
You seem to have an extra closing braces ) in the end i.e toString()))). It should be one less e.g.
select count(acc.account_id) from daily_account acc where acc.opening_date < '"+ new Date((Integer.parseInt(FromYearComboBox.getSelectedItem().toString())-1900),FromMonthComboBox.getSelectedIndex(),Integer.parseInt(FromDateComboBox.getSelectedItem().toString())).toString()+"'";
One note This is really making your query string complex to maintain. Try constructing the date string before hand and then append in the query.
Another Note: Date constructor with arguments is deprecated, and it also seems that you really don't need the date but string. In that case, why don't you write something simple as :
String dateStr =
String.valueOf(Integer.parseInt(
FromYearComboBox.getSelectedItem().toString())-1900)
+ FromMonthComboBox.getSelectedIndex()
+FromDateComboBox.getSelectedItem().toString();
String queryStr = "select count(acc.account_id) from daily_account acc "+
" where acc.opening_date < '"+ dateStr +"'";
Related
I have the below SP which I am trying to convert into simple Java inline query :
CREATE OR REPLACE PROCEDURE public.spdummytable(
par_zone_no integer,
par_fpsallocid integer,
INOUT p_refcur refcursor)
LANGUAGE 'plpgsql'
AS $BODY$
BEGIN
OPEN p_refcur FOR
SELECT
z.zone_no,
m AS monthnumber,
COALESCE(fpsallocid, par_FPSallocid) AS fpsallocid,
to_char((CAST ('2000-01-01' AS TIMESTAMP WITHOUT TIME ZONE))::TIMESTAMP + (COALESCE(aw.month, m) - 1::NUMERIC || ' MONTH')::INTERVAL, 'Month') AS monthname,
week1,
week2,
week3,
week4
FROM (SELECT par_Zone_No AS zone_no) AS z
CROSS JOIN (SELECT 1 AS m
UNION SELECT 2
UNION SELECT 3
UNION SELECT 4
UNION SELECT 5
UNION SELECT 6
UNION SELECT 7
UNION SELECT 8
UNION SELECT 9
UNION SELECT 10
UNION SELECT 11
UNION SELECT 12) AS moty
LEFT OUTER JOIN anotherTable AS aw
ON z.zone_no = aw.zone_no AND
aw.month = moty.m AND
COALESCE(fpsallocid, par_FPSallocid) = par_FPSallocid;
END;
$BODY$;
ALTER PROCEDURE public.spdummytable(integer, integer, refcursor)
OWNER TO postgres;
This will fetch some weekly values for every month from Jan to Dec.
What I am trying is below :
public List<MyResponse> result = null;
Connection conn = DatabaseConnection.connect();
PreparedStatement stmt = conn.prepareStatement("call public.spdummytable(?,?,?,,....,cast('p_refcur' as refcursor)); FETCH ALL IN \"p_refcur\";");
stmt.setString(1, "8006");
stmt.setString(2, "8049");
----
----
boolean isResultSet = stmt.execute();
if(isResultSet) {
ResultSet rs = stmt.getResultSet();
while(rs.next()) {
MyResponse myResponse = new MyResponse();
myResponse.setSomeVariable(rs.getString("columnname"));
-----
-----
result.add(myResponse)
}
rs.close();
conn.close();
}
But I am confused on the query formation part from the above SP. This seems to be a complex conversion. Can someone please help form the inline query. Appreciate your help on this.
EDIT/UPDATE
If I am unable to explain myself, I just want to say that I need to form the postgresql SELECT query from the above SP. I know the PreparedStatement is wrong above, I am trying to form a basic sql query from the above SP . Changing/Modifying the SP is not an option for me. I am planning to cut the dependency from the database and control it over Java. Please help.
I don't think getResultSet works with a stored procedure like that but I'm unsure. You're operating on a cursor with your INOUT parameter. As suggested in the comments, this would be much easier with a set returning function.
Note: stored procedures didn't exist in Postgres before Postgres 11.
If you cannot convert this to a set returning function, you'll need to handle the cursor object in a different manner. Something like this:
CallableStatement stmt = conn.prepareCall("{? = call public.spdummytable(?,?) }");
stmt.registerOutParameter(1, Types.OTHER);
stmt.setString(2, "8006");
stmt.setString(3, "8049");
stmt.execute();
ResultSet results = (ResultSet) stmt.getObject(1);
while (results.next()) {
// do something with the results.
}
Set returning function:
CREATE OR REPLACE FUNCTION public.spdummytable
( par_zone_no INTEGER
, par_fpsallocid INTEGER
)
RETURNS TABLE ( zone_no INTEGER -- I don't know the data types of these fields
, monthnumber INTEGER
, fpsallocid INTEGER
, monthname TEXT
, week1 TEXT
, week2 TEXT
, week3 TEXT
, week4 TEXT
)
AS $$
BEGIN
RETURN QUERY
SELECT z.zone_no AS zn
, moty AS mo_num
, COALESCE(fpsallocid, par_FPSallocid) AS fpsid
, to_char((CAST ('2000-01-01' AS TIMESTAMP WITHOUT TIME ZONE))::TIMESTAMP + (COALESCE(aw.month, m) - 1::NUMERIC || ' MONTH')::INTERVAL, 'Month') AS mo_name
, week1 w1
, week2 w2
, week3 w3
, week4 w4
FROM (SELECT par_Zone_No AS zone_no) AS z
CROSS JOIN generate_series(1, 12) AS moty
LEFT OUTER JOIN anotherTable AS aw ON z.zone_no = aw.zone_no
AND aw.month = moty
AND COALESCE(fpsallocid, par_FPSallocid) = par_FPSallocid
;
END;
$$ LANGUAGE PLPGSQL;
You could also define your own return type and use RETURNS SETOF your_type. Use the same function body as above.
CREATE TYPE type_dummytype AS
( zone_no INTEGER -- I don't know the data types of these fields
, monthnumber INTEGER
, fpsallocid INTEGER
, monthname TEXT
, week1 TEXT
, week2 TEXT
, week3 TEXT
, week4 TEXT
);
CREATE OR REPLACE FUNCTION public.spdummytable
( par_zone_no INTEGER
, par_fpsallocid INTEGER
)
RETURNS SETOF type_dummytype
AS $$ ... $$
Then your prepared statement becomes something like this:
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM public.spdummytable(?, ?);");
stmt.setString(1, "8006");
stmt.setString(2, "8049");
All of the other java should be good to go.
I have this small piece of code, the scope is:
In the outter while: I calculate a "min" number (selected from the tempTable)
In the inner while: I "Select * from (tempTable) where (some conditions)" (im completly sure there is more than 1 row that matches these conditions) and then i update the min in each row selected (whithin other aspects not relevant)
The inner while is conditioned by rs.next() which (as it does in other parts of my code) it should iterate through every row that matches the condition ("Select * from (tempTable) where (some conditions)")
Basically the program should work as: getting a "min" value, then proceed to update each row with equal "min" and "min" = "min" + 1. So in the next iteration of the outter while the "min" should be 1 more.
Instead, what it does is: get "min" value, then update ONLY the first row that matches that min value and goes back to the outter while(which calculates the min again). In the end, the output is rather the same and it kinda works, but I would really appreciate if it worked as I intended to match other aspects of the program.
I think the problem comes from doing a select * from a TEMPtable which for some reason returns only 1 row (i've been investigating but couldnt find other people with the same issue, so i don't really know). As I mentioned, there is other parts of my code where I do the same select * NORMALtable and the ResultSet.Next() works as intended.
while( total_tfgs > 0 ) {
int tfgs_round = 0;
min = prepareStatement.executeQuery("SELECT MIN("+ PROFESORES_COL_TFGS +") FROM TEMP_TABLA_PROFESORES WHERE " + PROFESORES_COL_OBLIGA + " = 'SÍ'").getInt(1);
ResultSet rs = prepareStatement.executeQuery("SELECT * FROM TEMP_TABLA_PROFESORES WHERE " + PROFESORES_COL_TFGS + " = '" + min + "' AND " + PROFESORES_COL_OBLIGA + " = 'SÍ'");
while(rs.next()) {
prepareStatement.executeUpdate("UPDATE TEMP_TABLA_PROFESORES SET PROFESORES_COL_TFGS = PROFESORES_COL_TFGS + 1 WHERE PROFESORES_COL_ID = '" + rs.getInt(1) + "'");
tfgs_round = tfgs_round + 1;
}
total_tfgs = total_tfgs - tfgs_ronda;
}
Here i place code where it works as i want it to work:
Statement statement = con.createStatement();
ResultSet rsA = statement.executeQuery("SELECT * FROM " + TABLA_ALUMNOS);
while(rsA.next()) {
String idA = String.valueOf(rsA.getInt("ALUMNOS_COL_ID"));
String dniA = rsA.getString("ALUMNOS_COL_DNI");
String nombreA = rsA.getString("ALUMNOS_COL_NOMBRE");
String dataA[] = {idA, dniA, nombreA};
DefaultTableModel tblModel = (DefaultTableModel) table_Alumnos.getModel();
tblModel.addRow(dataA);
table_Alumnos.setModel(tblModel);
}
PD: while redacting this i changed some variables to english (in the first code snipet) so it would be more legible(tfgs_round,total_tfgs), so if there is some misspell or something, thats not the problem. Please focus in the ResultSet select * from TEMP_TABLE (which i didnt change)
Thank you in advance for any help you can provide.
I would not call executeUpdate within the loop that is reading the ResultSet. That means you are using the statement for a second query while it is still involved in the first query. I would finish the first query entirely, close the ResultSet and then perform the update separately. If you really need to do an update while reading a ResultSet, I would build a new statement for it.
public ArrayList searchCustomer(String cid) throws SQLException {
ArrayList searchCustList = new ArrayList();
PreparedStatement pStmt = connection.prepareStatement("select * from customer where (custID = ? OR firstName LIKE ?)");
pStmt.setString(1, cid);
pStmt.setString(2, "%" + cid + "%");
please explain last command i used one text field for search customer by name or ID can any body explain last line
Your question is unclear, but if you want to understand :pStmt.setString(2, "%" + cid + "%");
Then it set the second parameter in sql query to the value of cid variable, and add % around
Adding % around, mean in an SQL Like 'any character', so having %cid% mean anything containing cid in it.
As the actual query use cid for either custId or firstName, it mean that it look for user having a specific id, or having in its firstname the id.
Which is strange, and looks like more a bug, than a logical query, but maybe it come from old legacy having some id in firstname, who knows
I want to filter my table to show records by month so i make a textboxes for the user input. Now i dont know if my query is correct. I dont have any error but also doesnt have any results. I use LIKE because i dont have specific day provided. Can someone suggest a better way?
ConnectToDatabase conn = null;
conn = ConnectToDatabase.getConnectionToDatabase();
String query = "Select * from inventoryreport where InDate LIKE "+txtYear.getText()+""+ txtMonth.getText()+"";
conn.setPreparedStatement(conn.getConnection().prepareStatement(query));
conn.setResultSet(conn.getPreparedStatement().executeQuery());
java.sql.ResultSetMetaData metaData = conn.getResultSet().getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
LIKE it's wrong choise becouse your db doesn't use index and will be slow (and doesn't work).
The query is like this:
SELECT * FROM inventoryreport WHERE YEAR(Date_column) = 2014 AND MONTH(Date_column) = 3;
So your code is:
String query = "Select * from inventoryreport where YEAR(InDate) = " +txtYear.getText()+" AND MONTH(InDate) = "+ txtMonth.getText();
I think it is a small mistake in the date format:
Your format : YYYYMM (no seperation symbol)
Right format: YYYY-MM-DD (with a '-' to seperate)
I think
String query = "Select * from inventoryreport where InDate LIKE "+txtYear.getText()+"-"+ txtMonth.getText()+"-00";
should fix it, if your database only includes monthly exact values.
Otherwise you should use
Select * from inventoryreport where InDate BETWEEN '2014-03-18' AND '2014-03-20'
A SQL query can take advantage of indexes when a column in not surrounded by a function. The following where clause would allow the use of indexes:
SELECT *
FROM inventoryreport
WHERE Date_Column >= str_to_date(concat_ws('-', txtYear.getText(), txtMonth.getText(), '01'), '%Y-%m-%d') and
Date_Column < adddate(str_to_date(concat_ws('-', txtYear.getText(), txtMonth.getText(), '01'), '%Y-%m-%d'), interal 1 month)
Although more complicated, all the manipulations are on constants, so the query engine can still take advantage of an index on Date_Column.
I'm trying to change a value Dr_status that only contain one int even 0 or 1. So if Dr_status equal to 1 change it to 0 and vice versa.
Here is the code :
String query = "Select Bluetooth_Address FROM dr";
String str = "40D32DBBE665";//in the database I have only two fields in `Bluetooth_Address` column 40D32DBBE665 and another value
String check = "";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
PreparedStatement preparedStmt= con.prepareStatement("update `dr` set `Dr_status` = '1'");
PreparedStatement preparedStmt1= con.prepareStatement("update `dr` set `Dr_status` = '0'");
dbtime = rs.getString(1);
if (dbtime.equals(str)){
check = "Select `Dr_status` From `dr` Where `Bluetooth_Address` = " + " " + str ;
if(check.equals(0)){
preparedStmt.executeUpdate();
}
if(check.equals(1)){
preparedStmt1.executeUpdate();
}
I don't know where is the problem !!! please help.
Thanks in advance.
I give +1 to the answer from #Marcelo Hernández Rishmawy. Instead of testing the condition in Java code, do the test and the update in an SQL expression that converts 0 to 1 and 1 to 0 automatically, for the rows that match your Bluetooth address condition.
I'll also give you a tip that in MySQL, 1 and 0 are integers, but they are also used for true and false. So you can use either of the following tricks to make the statement more compact:
"update `dr` set `Dr_status` = ! `Dr_status` where `Bluetooth_Address = " + str
This trick works too:
"update `dr` set `Dr_status` = 1 - `Dr_status` where `Bluetooth_Address = " + str
It's a nice way to simplify, but FWIW it's specific to MySQL, not standard SQL. Other databases brands use proper boolean values, not 1 and 0.
Re your comment: the error is not related to the solutions above, it's because you're interpolating a string of hex digits. You need to either quote the string, or better yet use a query parameter.
You should learn how to use query parameters in any case, because they're good for writing secure code to defend against SQL injection issues, and it's generally easier and more robust than trying to interpolate variables into SQL query strings.
See Using Prepared Statements at The Java Tutorials.
Use something similar to:
"update `dr` set `Dr_status` = CASE `Dr_status` WHEN '1' THEN '0' ELSE '1' END CASE Where `Bluetooth_Address` = '" + str + "'"
The line if(check.equals(0)){ is invalid. check is a String and will never equal 0