A strange behaviour of select query just came up on my way while im doing a task for the uni.Im pulling data from a table i got on my oracle db.
selectString = "select * from reservation";
prestatement = dbConnection.prepareStatement(selectString);
rs = prestatement.executeQuery(selectString);
while (rs.next()) {
String rdate = rs.getString("reservdate").substring(0, 10);
jComboBox1.addItem(rdate);
//....
//....etc..
The thing is that what is displayed on my combo box is a think like '1999-10-10'
After that i have to pull some data where i must select the ones with the date of the selected item on the combo box.Well there's my problem.
String x = String.valueOf(jComboBox1.getSelectedItem());
selectString="select * from reservation where reservdate='"+x+"'";
//...etc..
After i run that im getting an sql exception with message : Message: ORA-01861: literal does not match format string
I searched a little bit the web and found that if i run this select query everything works fine
selectString="select * from reservation where reservdate='10-OCT-99'";
So my question is, what is the best way to make this work.I mean should i try edit all the dates from combo box to this format? or im doing something wrong all the way and should change that?
Thanks in advance.
You can either:
1- Override your related class' (whatever object that getSelectedItem returns, in this particular case its already a String and you may not need that String.valueOf() call) toString method to achieve the needed format of yours. (Kind of bad to do)
2- Let Oracle DB handle it with its TO_DATE function (Kind of a better practice to do)
"TO_DATE(yourDateString,dateFormat)"
String date = String.valueOf(jComboBox1.getSelectedItem());
selectString="select * from reservation where reservdate= TO_DATE('" + date + "','DD-MON-YY')";
And to prevent SQL injections, using the latter approach with a PreparedStatement would look like this:
String date = String.valueOf(jComboBox1.getSelectedItem());
String selectString="select * from reservation where reservdate= TO_DATE(?,'DD-MON-YY')";
PreparedStatement preStatement = dbConnection.prepareStatement(selectString);
preStatement.setString(1,date);
ResultSet rs = preStatement.executeQuery();
Official Docs
Related
I am trying to retrieve data from DB2 using Java prepared statement
String select_statement = "SELECT * FROM schema_name.table_name where NME='xxx002' and LINE =7200 and FILE_NME='720001042021XYZ002' with ur";
try (Connection connection = DataBaseConnection.getGeoCarDBConnection_TESTDATA();
PreparedStatement ps = connection.prepareStatement(select_statement);) {
ResultSet rs = null;
rs = ps.executeQuery();
}
The problem I am facing is that I include the FILE_NME in the where clause of the query, as shown above, 0 rows are returned. But any other string fields can be passed and I get the desired number of rows.
Any integer fields in the where clause works too.
But only the string fields that are large(In this case, FILE_NME field) are not working. In the DB2 table, where I am pulling the data from, the FILE_NME field is of varchar(30).
Things that did not work for me was
String select_statement = "SELECT * FROM schema_name.table_name where NME='xxx002' and LINE =7200 and FILE_NME = ? with ur";
then I set the String value using,
ps.setString(1, "'720001042021XYZ002'")
ps.setString(1, "720001042021XYZ002")
Both did not work.
None of the google links were helpful. Have spent more than a day on it.
This code used to work flawlessly before, Even the java version hasn't changed(as per my knowledge)
I am running it in windows 10.
Java version : 1.8 ((build 1.8.0_221-b11))
I run the same query in the database client and it works.
Someone please help me or point me in the right direction. I don't know what I am missing
Thank in advance
The problem was that there was indeed no data, I was checking the same query in the database client in a different environment. I am closing this.
I have table called mpi which contains 23 columns. I have introduced the search field with button for every column where user can enter the query to fetch the records using query
query="select * from mpi where Genus ='"+genus+"'
Now I want to fetch records by giving keywords using LIKE %% but it is not working and not giving any records but if type type the full name it is working perfectly. Here is the code
String uname=request.getParameter("uname");
String full="%"+uname+"%";
dbconn=new DatabaseConnection();
conn=dbconn.setConnection();
pstmt=conn.prepareStatement("select * from mpi where Genus LIKE ?");
pstmt.setString(1, full);
res=pstmt.executeQuery
Could any one tell me where is the mistake and why I am not getting the records when I use half keyword like %keyword%.
It works (apart from the missing parentheses) and the approach with a prepared statement is entirely correct.
However I have seen a couple of code pieces like that, and always the problem lay with variables mix-up or not closing, or simple oversight. Better declare as close as possible.
try (ResultSet res = pstmt.executeQuery()) {
while (res.next()) {
..
}
} // Automatically closes res.
Also handle the life-cycle of pstmt correctly, with closing.
I having difficulties on retrieving data from multiple tables. It is going to be a search form and its a relational database.
Question1: How do I retrieve data from multiple tables now?
Question2: At the same time another problem I face is that I can not get any results if I try to search only by Name or Lastname. I get results only when I use date of birth. Why?
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
java.io.PrintWriter out = response.getWriter();
Connection conn = null;{ // while there is no connections, proceed to the next step
try {
Class.forName("org.postgresql.Driver"); // importing the driver to use the getConnection method
conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/caglar", "postgres", //?searchpath=cag
"abracadabra");
System.out.println("Connected to the database"); // console message
String agent_name = request.getParameter("givenname"); // variable - reads from user input
String agent_lastname = request.getParameter("familyname"); // variable - reads from user input
String dob = request.getParameter("birthyear"); // variable - reads from user input
ArrayList al=null;
ArrayList agent_list =new ArrayList();
//Problem 1: If dob is not given, it is not searching by name or lastname.
//String query = "select * from agent where givenname='"+agent_name+"' or familyname='"+agent_lastname+"' or birthyear='"+dob+"' order by givenname";
String query = "select * from agent where givenname='"+agent_name+"' or familyname='"+agent_lastname+"' ";
if(dob!=null && !"".equals(dob)) // if date of birth fiel is left blank, it will still proceed to the results page
query = query + " or birthyear='"+dob+"'"; // if date of birth exists, it will take it into account as well
query = query+ "order by givenname"; // ordering by first name
System.out.println("query" + query); // console message
Statement st = conn.createStatement(); // connection statement
ResultSet rs = st.executeQuery(query); // executing our query
while(rs.next())
{
al = new ArrayList();
al.add(rs.getString(1));//id
al.add(rs.getString(2));//dob
al.add(rs.getString(3));//name
al.add(rs.getString(4));//lastname
System.out.println("al :: "+al);
agent_list.add(al);
}
request.setAttribute("agentList",agent_list);
To reiterate what the others are pointing out above, this is "dangerous" code. By not using PreparedStatements, you are opening up yourself to SQL Injection attacks - by which, a malicious user can craft a SQL statement to delete all the data in a table. As #craig-ringer points above, it would be trivial submit data that would delete the table from the database.
Having pointed that out, underlined it several times and highlighted it in a fluorescent yellow mark, lets move on and try to answer your questions:
1) You can query data from multiple tables by using SQL Joins. Here's a PostgreSQL tutorial on JOINS - there are many others out there, I just picked the first one I found.
2) Without the exact data in the database, and the exact parameters being supplied, it is difficult to answer - however, I imagine that the issue is case sensitivity. Comparisons in PostgreSQL are case sensitive - so if the family name in the database is 'Smith' and the parameter is 'smith', no data will be found. So, for simplicity, you'll need to covert both the parameter and the data to the same case e.g. lower. e.g. SELECT * FROM agent where LOWER(familyname)='smith'
I'd also point out that you may run into problems with date formatting - again, this would be addressed using prepared statements.
It appears you are quite new to java, SQL and JDBC; I would suggest you try and follow some tutorials and read some books. There's quite a lot to get to grips with - good luck!
Following on from one of my previous questions to do with method design I was advised to implemented my SQL queries as a parameterized query as opposed to a simple string.
I've never used parameterized queries before so I decided to start with something simple, take the following Select statement:
String select = "SELECT * FROM ? ";
PreparedStatement ps = connection.prepareStatement(select);
ps.setString(1, "person");
This gives me the following error: "[SQLITE_ERROR] SQL error or missing database (near "?": syntax error)"
I then tried a modified version which has additional criteria;
String select = "SELECT id FROM person WHERE name = ? ";
PreparedStatement ps = connection.prepareStatement(select);
ps.setString(1, "Yui");
This version works fine, in the my first example am I missing the point of parameterized queries or am I constructing them incorrectly?
Thanks!
Simply put, SQL binds can't bind tables, only where clause values. There are some under-the-hood technical reasons for this related to "compiling" prepared SQL statements. In general, parameterized queries was designed to make SQL more secure by preventing SQL injection and it had a side benefit of making queries more "modular" as well but not to the extent of being able to dynamically set a table name (since it's assumed you already know what the table is going to be).
If you want all rows from PERSON table, here is what you should do:
String select = "SELECT * FROM person";
PreparedStatement ps = connection.prepareStatement(select);
Variable binding does not dynamically bind table names as others mentioned above.
If you have the table name coming in to your method as a variable, you may construct the whole query as below:
String select = "SELECT * FROM " + varTableName;
PreparedStatement ps = connection.prepareStatement(select);
Parameterized queries are for querying field names - not the table name!
Prepared statements are still SQL and need to be constructed with the appropriate where clause; i.e. where x = y. One of their advantages is they are parsed by the RDMS when first seen, rather than every time they are sent, which speeds up subsequent executions of the same query with different bind values.
i'm working with java to extract values of a time column in table in mysql.
the code below show the query i do send.
String query="select id,time from table where Hour(time)<=32 ";
ResultSet res = stmt.executeQuery(query);
while (res.next()) {
String id = res.getString(1);
Time tc = res.getTime("time");
System.out.println(tc);
}
the time values can be negative (-56:00:00 meaning that we surpassed a certain delay.
the problem is that I get: java.sql.SQLException: java.sql.SQLException: Bad format for Time '-05:48:49' in column 2.
thanks for your help.
If the conversion done by the ResultSet implementation does not work for negative time values then you still can read the value as a String and implement your custom method to convert the String to a Date (and vice versa):
String query="select * from table where Hour(time)<=32 ";
ResultSet res = stmt.executeQuery(query);
while (res.next()) {
String id = res.getString(1);
Time tc = convertToDate(res.getString("time"));
System.out.println(tc);
}
// ....
}
private Time convertToDate(String s) {
// implement magic here
}
As answered in your previous question you need to store and handle it as seconds which is stored as a signed integer.
The time type cannot be negative. You also cannot do math on a varchar/string and massaging it forth and back to a workable format as suggested by Andreas_D would only add unnecessary overhead. A signed integer is really the best datatype you can use for this. Use PreparedStatement#setInt() to store it and use ResultSet#getInt() to obtain it.
Maybe this answer is so late. But you can solve it just concating a string to the field you want.
I mean:
select id,concat(time,'') from table where Hour(time)<=32
Regards
Saul Hidalgo.
I think the problem is on the query itself.
When you run direcly the query [select * from table where Hour(time)<=32] does it not return you an error? I imagine the error is on the where clause [Hour(time)<=32]
The resultset does not have any information about the where clause. It just returns all the columns.
You need to check the columns return to check if you are not returning some strange type.