Android SQLite Query Syntax causing sqlite.SQLiteException - java

So i have a section in my database where i need to do a join the tables look like this...
______________ _______________
|Vehicle | |Car |
|--------------| |---------------|
|_id PK | |_id PK |
|Warehouse | |VehicleId FK |
|Location | |Make |
|VehicleKey | |Model |
|______________| |_______________|
The Car VehicleID Foreign key is from the Vehicle Primary key. What I want to return is a cursor for each vehicle.
Warehouse Location Make Model
I'm not sure how I would construct the SQLite statement, can anyone give me a hand?? So far I have this as my method to retrieve all of the vehicles
public Cursor getCars()
{
Cursor c = database.query("SELECT Vehicle.Warehouse, Vehicle.Location, Vehicle.VehicleKey, Car.Make," +
" Car.Make FROM Vehicle INNER JOIN Car" +
"ON Vehicle Vehicle._id = Car.VehicleId",
null, null,null,null,null,null,null);
return c;
}
I'm pretty new to this way of doing database manipulation as I would normally have it done for me by a builder as I have only ever worked in c#. Can anyone help me out trying to get the correct results?
There is an error produced, but I think it's because of syntax of the sqlite statement
android.database.sqlite.SQLiteException: near "SELECT": syntax error (code 1): , while compiling: SELECT * FROM SELECT Vehicle.Warehouse.........

There are no overloaded methods for query that accept a Sql String as a parameter.
See the documentation for the query methods here.:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
The first parameter is usually the table name.
The system is trying to build a Sql query using your whole query as the table name therefore you get a query such as "SELECT * FROM SELECT Vehicle..." etc
Either supply the correct parameters to the query method or use the rawQuery method which expects a standard Sql string.

String table = "Vehicle v INNER JOIN Car c ON Vehicle v._id = c.VehicleId";
String[] columns = new String[]{ "v.Warehouse", "v.Location", "v.VehicleKey", "c.Make"};
/*String where condition for example "where v.id = 1" 3rd parameter is your where codition in your db.query function */
/*db.query with where condtion : Cursor c = db.query(table,columns,"where v.id = 1",null,null,null,null,null);*/
Cursor c = db.query(table,columns,null,null,null,null,null,null);
Please review your query since i don't see patient Table in your join

You may edit your query using this syntax :
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;

Related

List of columns in sql query

I have a query using various joins, and I just need the list of columns which are returned by this query. I done it in java, by asking only one row with rownum=1 and getting column name for value.The problem is if there is no data returned by that query.
For ex.
select * from something
and if there is any data returning by this query then it will return col1,col2,col3.
But if there is no data returned by this query, then it will throw error.
What I need is
Is there any way that I can run
desc (select * from something)
or similar to get list of columns returned by query.
It can be in sql or JAVA. Both methods are acceptable.
In my application, user passes the query, and I can add wrapper to the query but I cant modify it totally.
The flow of application is
query from user -> execute by java and get one row -> return list of columns in the result set.
you can use ResultSetMetaData of resultset
for example :
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int countOfColumns = rsmd.getColumnCount();
for(int i = 1; i <= countOfColumns ; i++ )
System.out.println(rsmd.getColumnName(i));
you could maybe convert your query to a view, you can then see the columns in the view by querying user_tab_columns
select * from user_tab_columns
The Oracle equivalent for information_schema.COLUMNS is USER_TAB_COLS for tables owned by the current user, ALL_TAB_COLS or DBA_TAB_COLS for tables owned by all users.
Tablespace is not equivalent to a schema, neither do you have to provide the tablespace name.
Providing the schema/username would be of use if you want to query ALL_TAB_COLS or DBA_TAB_COLS for columns OF tables owned by a specific user. in your case, I'd imagine the query would look something like:
String sqlStr= "
SELECT column_name
FROM all_tab_cols
WHERE table_name = 'users'
AND owner = ' || +_db+ || '
AND column_name NOT IN ( 'password', 'version', 'id' )
"
Note that with this approach, you risk SQL injection.

Error when changing datatype of column in SQL Server DB - Java

I made a query in Java which changes one column's datatype in another. It works fine until it tries to change type. It finds all columns in DB with specified datatype, but cannt change it.
Here is my code:
st = conn.createStatement();
rs = st.executeQuery("SELECT a.name as ColName, o.name AS TableName"
+ "FROM sys.syscolumns AS a"
+ "INNER JOIN sys.systypes AS b ON a.xtype = b.xtype AND b.name = 'char' AND a.length = 255"
+ "INNER JOIN sys.objects AS o ON a.id = o.object_id WHERE (o.type = 'u') AND (o.schema_id = 1)");
ResultSet rsPom;
while (rs.next()){
String tName=rs.getString("TableName");
String cName=rs.getString("ColName");
System.out.println(tName+" "+cName);
rsPom=st.executeQuery("ALTER TABLE "+ tName+" ALTER COLUMN "+cName+" nvarchar(255)");
}
And here is my Exception:
com.microsoft.sqlserver.jdbc.SQLServerException: The object 'CK_TimeInstant_frame_default' is dependent on column 'frame'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:792)
at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:689)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(SQLServerStatement.java:616)
at DataTypeChanger.changeDataType(DataTypeChanger.java:50)
at DataTypeChanger.main(DataTypeChanger.java:36)
Does anyone knows what is all about, and what can I do?
Firstly, my apologies about the sarky comment above.
The reason you receive this error is because your alter script isn't taking any action with respect to constraints. Columns which are the target of constraints (Unique, Foreign Key, Default, etc) can't be modified unless the constraint is first dropped. In which case you'll probably need to add the constraints back afterwards.
I've assumed your earlier (deleted) comment still holds, viz that you do not require to create the constraints again after they have been dropped.
Re : How do I drop all constraints
Disclaimer : Back up your database before you try this, but the following MIGHT work. It is a destructive one way operation.
declare #sql nvarchar(2000);
while(exists(select 1 from sys.objects WHERE type_desc LIKE '%CONSTRAINT%'))
begin
BEGIN TRY
SELECT TOP 1 #sql=('ALTER TABLE ' + SCHEMA_NAME(schema_id) + '.[' + OBJECT_NAME(parent_object_id)
+ '] DROP CONSTRAINT [' + OBJECT_NAME(OBJECT_ID) + ']')
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT%'
ORDER BY NEWID();
exec (#sql);
END TRY
BEGIN CATCH
END CATCH
end;
GO
Rationale: The TRY CATCH is required because there is no guarantee that we will get the order of dependencies correct when dropping constraints (e.g. FK dependent on PK), so we basically squash the error and try drop another random constraint (ORDER BY NEWID())
Reference : Based on this query here, but extended to all constraints
SqlFiddle Here

JAVA mySQL JOIN 2 tables

Hey guys I'm looking to get information out of 2 tables to create a JTABLE with that information.
The tables I am look at are 'shipments' and 'customers'
Where shipments takes the form of
shipNumber | shipperID | destID | size | weight
and customers takes the form of
ID | lastName | firstName | street | city | state | zip
The shipperID and destID both refer to a customer ID.
I am trying to get the city/state information out of the customers table that corresponds to the shipperID and destID.
I have tried the following
query = "SELECT shipments.shipNumber, customers.city, customers.state, customers.city, customers.state FROM shipments, customers WHERE shipments.shipperID = customers.ID";
Realizing that the duplicate customers.city/customers.state is populating the same information twice.
As previously said, I am trying to get the shipper city/state and destination city/state.
I also tried
query = "SELECT shipments.shipNumber, customers.city, customers.state, customers.city, customers.state, shipments.size"
+ " FROM shipments"
+ " INNER JOIN customers ON customers.id = shipments.shipperID";
Where this gives the same information.
I am not sure how to reference the destID = customer.id
Thanks,
Mike
The usual trick is to join with the customers table twice, once for the shipper and once for the destination:
SELECT shipments.shipNumber,
shipper.city, shipper.state,
dest.city, dest.state,
shipments.size
FROM shipments
INNER JOIN customers shipper ON shipper.id = shipments.shipperID
INNER JOIN customers dest ON dest.id = shipments.destID

Java - Inner Join with 3 Table

i doing some project using Java(netbeans sw) and link to Microsoft Access.
The problem occur when i need to inner join 3 tables together from Microsoft Access,
i have no problem to inner join 2 tables together
rsUpdate =
stmtUpdate.executeQuery("SELECT * FROM A_User Inner Join A_PC ON A_USER.SN = A_PC.SN");
which i able to get the result. But not inner join with 3 tables
rsUpdate =
stmtUpdate.executeQuery
("SELECT * FROM A_User Inner Join A_CPU ON A_USER.SN = A_CPU.SN , Inner Join A_Software ON A_CPU.SN = A_Software.SN")
For the SQL above I have 3 "A" table separately for USER | CPU | Software|
USER PK is SN | CPU FK is SN | Software PK is SN |
The Error I got java.sql.SQLException:Characters found after end SQL statement
Thanks
rsUpdate =
stmtUpdate.executeQuery
("SELECT * FROM A_User
Inner Join A_CPU ON A_USER.SN = A_CPU.SN
Inner Join A_Software ON A_CPU.SN = A_Software.SN");
no need for ',' here... try this above code
For Ms Access, when you JOIN more than table, the syntax is different. It should be this way:
SELECT *
FROM ((a_user
INNER JOIN a_cpu
ON a_user.sn = a_cpu.sn)
INNER JOIN a_software
ON a_cpu.sn = a_software.sn)
There should be no comma after the first join
rsUpdate =
stmtUpdate.executeQuery
("SELECT * FROM A_User Inner Join A_CPU ON A_USER.SN = A_CPU.SN Inner Join A_Software ON A_CPU.SN = A_Software.SN")
Problem Solved
For example -
Table A | Username(PK)| Address|
Table B | ID | Phone | Username(FK)|
Table C | SN | Brand | Model | Username(FK)
rs = st.executeQuery
("SELECT * FROM (A Inner Join B on A.Username = B.Username) Inner Join C on A.Username = C.Username");
if anyone looking for inner join 3 tables together by Using JAVA and Link to Access
use the referenece above.
Make sure you must link the table relationship in Access before run the java program if not it will pop out "ERROR IN ROW"
Thanks everyone who helping me :)

Calling a PostgreSQL function from Java

I have written a function that I would like to call in Java. But I don't think it is able to do anything with the query that I passed. Following is my code from java:
String QUERY_LOCATION = "select (license_plate) as test from carInst( (select category_name from reservation where rid = ?) , (select lname from reservation where rid = ?))";
//PreparedStatement check_location = null;
PreparedStatement check_location = connection.prepareStatement(QUERY_LOCATION);
check_location.setInt(1, rid);
check_location.setInt(2, rid);
rs = check_location.executeQuery();
if (rs.next()) {
System.out.print("Car found: "+rs.getString("test")+"\n");
license_plate = rs.getString("test");
update_reservation.setString(5, license_plate);
bool = false;
} else {
System.out
.print("There is no car available\n");
}
And following is my stored procedure written in PL/pgSQL (PostgreSQL):
CREATE OR REPLACE FUNCTION carInst(cname varchar(20), loc varchar(20) )
RETURNS TABLE (license_plate varchar(6) ) AS $$
BEGIN
DECLARE cur CURSOR
FOR SELECT carinstance.license_plate, carmodel.category_name, carinstance.lname FROM carinstance,carmodel
WHERE carinstance.mid = carmodel.mid ;
BEGIN
FOR rec IN cur LOOP
RETURN QUERY SELECT distinct carinstance.license_plate FROM Carinstance
WHERE rec.category_name = cname
AND rec.lname = loc
AND rec.license_plate=carinstance.license_plate;
END LOOP;
END;
END;
$$ LANGUAGE plpgsql;
When I run the code in Java, the print statement prints a null value for Car found. I would really appreciate some help here.
Problems
Most importantly, the query in the LOOP is nonsense. You select rows from carinstance, but all conditions are on rec. This select all rows multiple times.
One END too many. FOR has no END, only LOOP has.
Whenever you feel the temptation to work with an explicit cursor in plpgsql, stop right there. Chances are, you are doing it wrong. A FOR loop has an implicit cursor anyway.
Don't mess with mixed case identifiers without double quotes. I converted all identifiers to lower case.
You use one simple query, spread out over a cursor and another query. This can all be much simpler.
Solution
Try this simple SQL function instead:
CREATE OR REPLACE FUNCTION car_inst(_cname text, _loc text)
RETURNS TABLE (license_plate text)
LANGUAGE sql AS
$func$
SELECT DISTINCT ci.license_plate
FROM carmodel cm
JOIN carinstance ci USING (mid)
WHERE cm.category_name = $1
AND ci.lname = $2
$func$;
Call:
SELECT license_plate AS test FROM car_inst(
(SELECT category_name FROM reservation WHERE rid = ?)
, (SELECT lname FROM reservation WHERE rid = ?)
);
Or build it all into your function:
CREATE OR REPLACE FUNCTION car_inst(_cname text, _loc text)
RETURNS TABLE (license_plate text)
LANGUAGE sql AS
$func$
SELECT DISTINCT ci.license_plate
FROM carmodel cm
JOIN carinstance ci USING (mid)
JOIN reservation r1 ON r1.category_name = cm.category_name
JOIN reservation r2 ON r2.lname = ci.lname
WHERE r1.rid = $1
AND r2.rid = $2;
$func$;
Call:
"SELECT license_plate AS test FROM car_inst(? , ?)";
Remember: The OUT parameter license_plate is visible anywhere in the body of the function. Therefore you must table-qualify the column of the same name at all times to prevent a naming collision.
DISTINCT may or may not be redundant.

Categories