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.
Related
It's been long fight between mysql and sql lite date issue. I have a complex query which returns multiple data.
I read server Json objects and store them in sql lite android was fine.
So i did a query which is like below one
"SELECT * FROM " + MAIN_TABLE + " LEFT OUTER JOIN " + SERVICE_INFO_TABLE + " ON ServiceInfo.main_id = MAIN_TABLE._ID"
+ " LEFT OUTER JOIN " + M_USER_TABLE + " ON M._ID = ServiceInfo.m_id"
+ " LEFT OUTER JOIN " + U_TABLE + " ON MAIN_TABLE.u_id = U_TABLE._ID"
The problem starts when i read the MAIN_TABLE which contains creation_time and upation_time, The SERVICE_INFO_TABLE also contains creation_time, updation_time.
However the table contains different date and time respectively. The cursor returns same date and time for all entity.
It seems the cursor method got confused and return same data and time read from ServiceInfo table.
I dig deeper into debugging mode while SQL lite read the query, i saw strange things happening over there. Below is the reading example
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
do {
Log.d("dummy", "dummy stopper");
VParcelable vParcelable = new VParcelable();
vParcelable.setId(cursor.getInt(cursor.getColumnIndex(VEntry._ID)));
vParcelable.setModel(cursor.getString(cursor.getColumnIndex(VEntry.MODEL)));
vParcelable.setYearMdl(cursor.getInt(cursor.getColumnIndex(VEntry.YEAR_MODEL)));
vParcelable.setCreationTime(cursor.getString(cursor.getColumnIndex(VEntry.CRE_TIME)));
vParcelable.setUpdationTime(cursor.getString(cursor.getColumnIndex(VEntry.UPA_TIME)));
So the ServiceInfo table also contains the same creation_time and updation_time.
vParcelable.setCreationTime(cursor.getString(cursor.getColumnIndex(VEntry.CRE_TIME)));
mColumns from cursor debugging mode shows "updation_time" and "creation_time" for VTable and same as for ServiceInfo table.
Is that problem of sql lite couldn't differentiate table column names?
That really sucks.
Help please.
Thanks
Your date string '15-04-2015' is in a DD-MM-YYYY format but it appears it is being treated as MM-DD-YYYY at some point. You aren't showing ANY code in your question, so I can't tell you exactly how you need to solve this. In general you need to specify to the database the date format you are using, or switch to storing it as a string or integer in the database. You might look at some of the answers to this question: Best way to work with dates in Android SQLite
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?
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.
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.
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.