SQL Query in Java - Unable to select two columns - java

I currently have a search function for my database where I have a Java front-end GUI.
At the moment in Java I have a SELECT statement that checks what one enters is LIKE something. The problem that I am having is that within my SELECT statement, I want to also get the forename column.(I am fairly new to this).
Below is a snippet of the code:
/*
* Search method
*/
public void search()
{
// search function - person query
String sqlPerson = " SELECT * FROM `person` "
+ "WHERE ((`person`.`Surname`LIKE ?) "
+ "OR (`person`.`Forename` LIKE ?) "
+ "OR (`person`.`Person_Id` LIKE ?) "
+ "OR (`person`.`aka` LIKE ?) "
+ ")ORDER BY `person`.`Surname` ASC ";
Does anyone know how I can select both forename and surname so it gets both columns because at the moment when I search, I can only do it by one column (As I am currently using an OR).
Thanks

Your query already gets all colums from that table. What is your problem? Just replace the correct ? with the search term you are looking for.

Related

How can I set a date variable with normal string variables in my jpql code?

I have a query that has to be executed in my application. On the front end side, a user should be able to make a search in the search bar. Every time he will write in the search box, we will automatically take this input and send a request to retrieve the corresponding data. The problem here is the date, the user should be able to select the data returned according to the specific categories. When he select a date, all the products with this corresponding date have to be returned.
This is the code below:
String sql = "SELECT t FROM tables t WHERE (t.a LIKE ?1 OR "
+ " t.b LIKE ?1 "
+ "OR t.c LIKE ?1 "
+ "OR t.d LIKE ?1 OR t.e LIKE ?1 "
+ "OR t.f LIKE ?1 "
+ "OR t.g LIKE ?1 "
+ "OR t.u_date LIKE TO_DATE(?1,'dd/MM/yyyy') "
+ "OR t.y_date LIKE TO_DATE(?1,'dd/MM/yyyy') ) "
+ "OR t.num LIKE ?2)";
lstMvt = em.createQuery(sql)
.setParameter(1,isDate == true ?search_value:search_value+"%")
.setParameter(2, num+"%")
.setFirstResult(start)
.setMaxResults(limit)
.getResultList();
In my code, I have written a helper function to check whether the search value entered is a date or a normal string. So when injecting the parameters, isDate variable tells me that if the search is true(a date) then inject it directly but if it is a normal string inject it with % as it is a LIKE clause.
The problem is being caused by the dates variable in the query. When I search with a date value in the search box the data return correctly, but when I try to search with a non-date value, an exception is thrown. I know the problem is from the dates variables because I had commented them to test and it was working properly.

Number of characters in sql query result

I am using Spring 3.1.1 with Hibernate 4 and a MSSQL database. Finally, I have been able to query my database with joins in my table that returns the correct answers. Although, it seems that it does not return the entire strings of my messages, but cuts at 29/30 digits. Here is my query:
SQLQuery sql = this.getCurrentSession().createSQLQuery(
"SELECT event.id as eventid, CAST(event_type.type_name AS varchar) as eventtype, event.check_date, event.event_date, event.status, CAST(event_message.message AS varchar) as eventmessage " +
"FROM event_log event " +
"LEFT JOIN event_type " +
"ON (event.event_type_id = event_type.id) " +
"LEFT JOIN event_message " +
"ON (event.event_message_id = event_message.id) " +
"WHERE event.event_type_id = " + jobId +
"ORDER BY eventid");
The result can be:
4506 Database 2014-01-15 14:14:15.02 2014-01-15 14:14:15.02 false Database-connection cannot be
Where the columns are id, task_name, check_date, event_date, status and the message-string at the end. .
The result goes to a ArrayList<Object[]> where I read row[0] etc. to get the entities in the row. The string message gets cut after 29 digits, which is disturbing. Why does it cut the string and how can I fix this? In my database the string exists in it's full and is entitled 400 characters max.
I know this is probably not the best way to query my database, but it will do for my application since it works.
You are using varchar without a length. Never do this!
Replace:
CAST(event_type.type_name AS varchar)
With something like:
CAST(event_type.type_name AS varchar(255))
In some contexts, the default length is 32. In some it is 1. In general, though, always specify the length.
EDIT:
Actually, you probably don't even need the cast. Why not just have event_type.type_name in the select list?

How to get meta data information of a sql query

I am using postgres 9.1 and java code for jdbc.
I may use a order by clause in my sql query string
I just want to get the meta data information of the query to find whether the query has order by clause or not. If it has then how many fields has been specified in the order by clause.
Ex:
order by age
order by age, name
order by age asc, name desc
In these example I just want to retrieve the number of parameters that are specified in the order by clause and their column names.
If your are getting your query as string you could simply parse it.
i.e. To figure out that ORDER BY is there
"SELECT * FROM MyTable ORDER BY SomeColumn".toLowerCase().indexOf("order by") // if it's return -1 query does not contains order by section otherwise it returns start index for first occurence "ORDER BY" in given string
For more complex searching in string you may need to use RegExp
You can do it by breaking an SQL query into part and then reassigning.
Like
String sql="SELECT NAME,COMPANY,FNAME,AGE FROM COMP_DATA JOIN PERSONAL_DATA WHERE (1=1) AND FNAME='Vaibs' ORDER BY AGE";
While writing in JAVA do as below.
Break Whole query into String parts and recombine it like this.
String strSQL = "SELECT " + "NAME"+",COMPANY"+",FNAME"+",AGE" + "FROM "
+ getTableName1(); //getTableName1() return tablename
strSQL+="JOIN "+ getTable2()+"";//getTable2() return tablename as well
String strWhere = " WHERE (1=1) " + " and FNAME='" + fname+ "';
String orderBySQL = " Order by " + i_will_return_string_to_order_by();
//return AGE in our case
String FinalString= strSQL +strWhere +orderBySQL ;
SOP order by to get what you want.
Hope that helped.

keep column name variable in Java INSERT INTO command with PreparedStatement?

I have the following problem:
I have two tables in one data base which consist of the same columns besides the name of the last column. I want to write data into them using Java.
I want to use the same preparedStatement for both tables, where I check with an if-command whether it is table1 or table2. table2 has amount10 as the name for the last column, table1 has amount20 for it. This number is stored in a variable within my code.
Below you can see a (simplified) example and how I tried to let the column name variable but it doesn't work. Is there any way to fix this without copying the whole statement and manually changing the number variable?
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount`+"number") VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount`+"number" = ? ; ";
PreparedStatement insertDataStmt;
This will not work since variables number and table are not going to be magically injected into your insertData string while you are changing them.
I'd to a method prepareInsertstatement(String table, String number) that would return correct PreparedStatement:
public void prepareInsertStatement(Connection conn, Strint table, String number) {
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount+"number"') VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount+"number"' = ? ; ";
PreparedStatement insertDataStmt = conn.prepareStatement(insertData);
return insertDataStmt;
}
Just remember to close the PreparesStatement when you don't need it any more.
I suppose that reason for that is invalid syntax. When you concatenate string for last column name you use code 'amount' + number. If your number value is 20, than concat result will be
'amount'20 that cause invalid syntax exception. Just move one extra ' after number.
"'amount" + number + "'"
Note: log, or just error that appears during this statement execution would be very useful to find right answer for your question.

Using one query in another in JDBC programming

I understand how to do this on paper in SQL, but am having trouble implementing this in Java (this is the first time I am actually programming JDBC stuff)
For example, say my database consists of:
movie(code, title, publisher)
customer(custno, name)
borrowed(custno, code)
And I want to find the name of customers who borrowed every movie by pubisher ABC
string no_of_ABC_movies = "SELECT COUNT(publisher), publisher FROM movie, WHERE movie.publisher = 'ABC'";
string no_of_cust_ABC_movies = "SELECT COUNT(name), name FROM customer, borrowed, movie, WHERE customer.custno = borrowed.custno AND borrowed.code = movie.code AND movie.publisher = 'ABC'";
String query = "SELECT name" +
" name FROM customer, borrowed, movie" +
" WHERE customer.custno = borrowed.custno AND" +
" borrowed.code = movie.code AND" +
" movie.publisher = 'ABC' AND" + " "
no_of_cust_ABC_movies + " = " + no_of_ABC_movies;
This isn't the exact database I am working with, but query will work and print out the names of people who borrowed movies from ABC without the last line, but says I have an error in SQL syntax with the last line so I guess I don't know how to use one query within another.
It depends on your DBMS, but every SQL variant I've seen requires parens around subqueries.
Try something like:
...
" movie.publisher = 'ABC' AND ("
no_of_cust_ABC_movies + ") = (" + no_of_ABC_movies + ")";
You have problem with double name field without being separated by a comma in your query.
If your code is exactly as listed above, you have compilation error just above the last line-missing + to concatenate strings.
If that's a typo below is my suggestion.
Remove duplicate select (use only one name) or
Separate names by a comma ( I don't see a point of selecting name twice though)
And your last line is wrong.. you can not compare two select queries that way.. Just add the required where clauses.
(You should read database joins first, and then solve your problem)
I like to get my queries working in the query browser or workbench, then copy them over to Java. It keeps it to one new thing at a time...
You're query actually starts with
SELECT name name FROM customer ...
The name column is duplicated - maybe that the problem.

Categories

Resources