I want to run the query: "DESCRIBE table_name;"
statement = this.connection.createStatement();
ResultSet rset = statement.executeQuery("DESCRIBE table_name");
and I got this error:
" java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement"
what is the problem?
DESC[RIBE] is a SQL*Plus command, not a SQL statement. The DESC command queries the Oracle data dictionary, something like:
select COLUMN_NAME, DATA_TYPE
from USER_TAB_COLUMNS
where TABLE_NAME = 'YOUR_TABLE'
DESC is a SQL*Plus command. SO, you cannot use it via JDBC/ODBC.
An alternative can be like this below.
select RPAD(COLUMN_NAME,30)||' '||DATA_TYPE||'('||DATA_LENGTH||')' as descr
FROM all_tab_cols
WHERE TABLE_NAME = UPPER('YOUR_TABLE') and owner=UPPER('SCHEMA_NAME');
all_tab_cols is a data dictionary table(view) which contains the table metadata
Oracle's Reference
describe user2.flights;
Here user2 is database name and flights is table name. Try this.
Or use next query
select *
from user_tab_columns
where table_name = 'MY_TABLE'
order by column_id;
Use this query.
column_id is the "order" of the column in the table.
You should ensure that 'MY_TABLE' is capitalised unless you've been adding tables with casing ( a bad idea ) in which case you need to use something like = "MyTable"
Related
Postgres query:
select t
from TableName t
where t.isActive=true
order by t.extcol->'desc'
This work's fine.
Need help with HQL query which will do the same job.
String query = "select t from TableName t where t.isActive=true order by t.extcol->'desc'"
newList = TableNameModel.executeQuery(query);
Method threw 'java.lang.IllegalArgumentException' exception.
context: there is a table TableName where one column is extcol which contains object. Need to sort TableName based on a property desc which present in extcol json object.
For HQL you have the wrong syntax for sorting.
It should be order by t.extcol desc without the arrow and quotes.
see https://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-ordering
I have SQL Server and I am using SQL management studio. What I want is to select default value of column of multiple tables in database.
For example I have database DB. In DB I have 3 tables - tableA, tableB and tableC.
All of them have the same columns. What I want is to get default values of columns 'Customers' for tables A,B and C.
It must be something like this:
SELECT Column_Default
FROM Information_Schema.Columns
WHERE Table_Schema = DB AND
Table_Name like 'table%' and
Column_Name = 'Customers'
But there is error in Table_Schema = DB. I am not sure it should look like this as SQL syntax. It is working as MySQL but not here.
SELECT COLUMN_DEFAULT
FROM Information_Schema.Columns
WHERE Table_Schema = 'dbo'
AND TABLE_NAME IN ('A','B','C')
AND COLUMN_NAME = 'Customers'
You were close, you just needed single quotes around your table schema name, also using the IN operator to explicitly specify your table names instead of using your wildcard search can make the query more robust if if a new table of a similar name is created.
I'm attempting to create a JDBC query with the following statement
String query = "SELECT COLUMN1,DATECOLUMN2 FROM tableName +
"where datediff(d,DATECOLUMN2,getdate()) <= 1";
st = conn1.createStatement();
rs = st.executeQuery(query); //receiving error here
I am receiving the following error message
java.sql.SQLException: "d" is not a recognized table hints option. If it is intended as a parameter to a table-valued function or to the CHANGETABLE function, ensure that your database compatibility mode is set to 90.
I'm sure the query isn't recognizing the datediff function for some reason I am not sure why since i was previously using HQL in the same application and retrieving the values.
In an attempt to use an alternative function I used
{fn TIMESTAMPADD( SQL_TSI_DAY, 1, CURRENT_TIMESTAMP)}
but it also failed I later on found that this is only used for Derby Database's
Can someone assist me in using the proper sql function to compare a date with the current date using JDBC
String query = "SELECT COLUMN1,DATECOLUMN2 FROM tableName "+
"where datediff(day,DATECOLUMN2,getdate()) <= 1";
You have a comma before from. Based on the error messages you are running this against SQL server.
String query = "SELECT COLUMN1,DATECOLUMN2 FROM tableName "
+" where datediff(d,DATECOLUMN2,getdate()) <= 1";
The comma after the "d" should be a dot:
where datediff(d.DATECOLUMN2,getdate())
--------------- ^ dot here
The posted snippet doesn't have a closing double quote between tableName and +, but I figure that is just a typo. However, in your real code, where precisely is the double quote? Is it directly after tablename, like this
String query = "SELECT COLUMN1,DATECOLUMN2 FROM tableName" +
or after the space that follows tablename, like this
String query = "SELECT COLUMN1,DATECOLUMN2 FROM tableName "+
It is very likely the former, because in that case the resulting query would look exactly the way as to cause the error you are getting. Take a look at this:
SELECT COLUMN1,DATECOLUMN2 FROM tableNamewhere datediff(d,DATECOLUMN2,getdate()) <= 1
You can see that where merges with the table name and datediff becomes an alias. What follows is interpreted as table hints. (You can specify table hints without WITH in older versions of SQL Server/older compatibility levels.) Consequently, SQL Server stumbles over d, as that is indeed an incorrect table hint.
I'm wondering if there is a way to return the column names of a results set (Oracle database, in Java) that would be generated IF I actually executed a query. For example, say I had SQL looking something like this:
select * from <complex table join>;
Is there a way to send this query to oracle and have it tell me just what the column names are on the result set it will return WITHOUT actually performing the query (because it is expensive)?
I think using a PreparedStatement could work:
PreparedStatement stmt = connection.prepareStatement("select ...");
ResultSetMetaData meta = stmt.getMetaData();
for (int col=0; col < meta.getColumnCount(); col++)
{
System.out.println("Column: " + meta.getColumnName(col + 1));
}
(Edit): I tried this with Oracle 11.2 and driver version 11.2.0.3 and it works.
If that fails you could simply append a where 1=0 to the query and execute it then. At least it will not return all the rows then (possibly also using Statement.setMaxRows() as well, just to be sure.
A final (yet pretty complicated) option would be to use dbms_sql to open, prepare and describe the statement. See the manual for details: http://docs.oracle.com/cd/E11882_01/appdev.112/e25788/d_sql.htm
You could try wrapping the query in an outer select and adding where 1=0 to prevent it from fetching any rows:
SELECT * from (
<your query here>
)
WHERE 1=0
SELECT
COLUMN_NAME
FROM
ALL_TAB_COLUMNS
WHERE
TABLE_NAME ='tableName';
is probably what you meant.. however it is still a query...just that instead of querying application tables you are querying special tables
same with answers that request metadata
How can I detect if a certain table exists in a given SQL database in Java?
You can use DatabaseMetaData.getTables() to get information about existing tables.
This method works transparently and is independent of the database engine. I think it queries information schema tables behind the scenes.
Edit:
Here is an example that prints all existing table names.
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
System.out.println(rs.getString(3));
}
Use java.sql.DatabaseMetaData.getTables(null, null, YOUR_TABLE, null). If the table exists, you will get a ResultSet with one record.
See DatabaseMetaData.getTables
For ALL ANSI-compliant databases:
(mySQL, SQL Server 2005/2008, Oracle, PostgreSQL, SQLLite, maybe others)
select 1 from information_schema.tables where table_name = #tableName
This is not a language-specific, but a database-specific problem. You'd query the metadata in the database for the existence of that particular object.
In SQL Server for instance:
SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[table]')
AND type in (N'U')
Write a query that queries the table/view that will list the tables (this is different depending on DB vendor). Call that from Java.
Googling information_schema.tables will help a lot.
Depending on the DB, you can do (MySQL)
SHOW TABLES
or (Oracle)
SELECT * FROM user_objects WHERE object_type = 'TABLE'
or another thing for SQL Server. Cycle through the results for MySQL or further filter on the Oracle one.
Why not just see if it is in sysobjects (for SQL Server)?
SELECT [name] FROM [sysobjects] WHERE type = 'U' AND [name] = 'TableName'
There is a JDBC feature, database vendor independent - see [java.sql.DatabaseMetaData#getTables()][1]
You can get the DatabaseMetaData instance by calling java.sql.Connection#getMetaData()
[1]: http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html#getTables(java.lang.String, java.lang.String, java.lang.String, java.lang.String[])
This is what worked for me for jdbc:derby:
//Create Staff table if it does not exist yet
String tableName = "STAFF";
boolean exists = conn.getMetaData().getTables(null, null, tableName, null).next();
if(!exists){
s = conn.createStatement();
s.execute("create table staff(lastname varchar(30), firstname varchar(30), position varchar(20),salary double,age int)");
System.out.println("Created table " + tableName);
}
Note that tableName has to be all caps.
For MS Access:
Select Count(*) From MSysObjects
Where type=1 And name='your_table_name_here'