H2 database change column's display name on fetch - java

I have table test on H2 database on in java with columns testID,testName and testAddr. When I run this query:
SELECT testID AS 'Your ID', testName AS 'Your Name', testAddr AS 'Your Address' FROM test;
I get the error:
org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "SELECT testID AS [*]'Your ID',testName AS 'Your Name',testAddr AS 'Your Address' FROM test;"; expected "identifier"; SQL statement [42001-214]
How do I get alias for my column names?

Thanks to #MarkRotteveel I got the answer
SELECT testID as "Your ID", testName AS "Your Name", testAddr AS "Your Address" FROM test;
was the correct way. Further, use java's ResultSetMetaData's getColumnLabel(int i) function to get these aliases.
These things were implicit in SQLite, but not in others.

Related

Java - regex on sql query

I need to apply a java regex on sql query string to calculate the count of it. I have to get what is between the "first select" and "from" of the principal query.
This is my example :
Query :
select name,(select age from subtable), adress from table where name in (select name from subtable1)
Result :
select count(*) from table where name in (select name from subtable1)
I was using replaceFirst("^(.*?)from", "select count(*) from") but it is not working because there is an sql query in the attribute.
Please anyone can help ?
You can solve your problem using this regex ^(.*?)from(?![^(]*\\)):
str = str.replaceFirst("^(.*?)from(?![^(]*\\))", "select count(*) from");
Output
select count(*) from table where name in (select name from subtable1)
The idea is match from that is inside () parenthesis.
Demo

The column name is not valid - error

I am getting this error while I am fetching value from resultset.
Error : com.microsoft.sqlserver.jdbc.SQLServerException: The column name company.short_name is not valid
CASE 1 :
select company.short_Name,location_name from company,location;
this query is executing fine on SQL Server but in my java code when I trying to retrieve value like resultset.getString("company.short_name"); that time this give the above error.
CASE 2 :
select company.short_Name short_name,location_name from company,location;
and retrieve value like resultset.getString("short_name"); than it work fine with both database MySQL and MSSQL.
I am migrating my database from MySQL to MSSQL.above case 1 is work fine in MySQL, but why it is not work in MSSQL?
resultset.getString("company.short_name"); is wrong here. No need to specifying fully qualified name while trying to fetch the data in your application. Just specify the column name like resultset.getString("short_name");.
Cause even though you say select company.short_Name ... query out the column name as short_Name since that's what defined in table schema.
In case both tables has same column which may result in ambiguity, give a alias name to the columns like
select company.short_Name as company_shortname,
location.short_Name as location_shortname,
location.location_name from company,location;
add the following to your application.properties file
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
When you do
select company.short_Name,location_name from company,location;
This query outs the column name short_Name and resultSet would also have short_Name
since the company.short_name doesnt exist you get an error.
the function resultset.getString(String columnLabel)
Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.
Parameters:
columnLabel the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column
Returns:
the column value; if the value is SQL NULL, the value returned is null
Throws:
SQLException - if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set
in the function resultset.getString(String columnLabel), the arg is a column name for executing sql, the statement select company.short_Name,location_name from company,location; will get a result set, which has table headers short_Name,location_name

Run Oracle query from Java

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"

aggregate function using alias name and fetch the result into the resultset using the Alias name given for that function which uses alias name

I have to perform calculation using aggregate function by specifying the alias name inside that function and retrieve the data into my resultset using the alias name given for that aggregate function... when I tried to do that I got an Exception saying "Invalid Identifier" how to resolve this?
To be more clear, Am using alias name inside my aggregate function and giving alias name for the final result obtained by this aggregate function. so now my question is how to fetch the value returned by the aggregate function into my resultset? When I try to retrieve that through my Resultset in java code, It is throwing Exception. how to resolve this issue?
my Query:
select customername,
to_char(dt,'ddmonyy'),
lpad(sum(AliasNAme2),15) as AliasName
from (
select customername,
dt,
sum(traffic) as AliasNAme2
from table
where dt >= trunc (SYSDATE -1)
group by customername,
dt,
0,
0,
0
)
group by customername,
to_char(dt,'ddmonyy'),
having customername = 'BB'
I got an error "Invalid Identifier" when I try to fetch the data using the following java code
rs.getInt("AliasName");
I think there is a space in rs.getInt("AliasName "). Please remove and check.

Insert from array<> java into table sql where not exists [duplicate]

Good evening
i have problem about a query of insert if not exist i have do it in another query and it worked
but now i have an array of class java Service
so i want test about the id : VLAN
because i execut every time and i want that not insert many time if it exist already on table sql
This is my query but they give me an error about it
for(Service srv:service){
srvDataLst.add(srv.getvlan());
PreparedStatement pst=conn.prepareStatement(
"INSERT INTO tout (VLAN,client,JR,vrf,address) "
+ "VALUES(?,?,?,?,?) SELECT DISTINCT "
+ "'"+srv.getvlan()+"' FROM dual WHERE NOT EXISTS("
+ "SELECT * FROM tout WHERE 'VLAN'='"+srv.getvlan()+"') ");
pst.setInt(1,srv.getvlan());
pst.setString(2,convertNullToEmptyString(srv.getdesc()));
pst.setString(3,convertNullToEmptyString(srv.getjr()));
pst.setString(4,convertNullToEmptyString(srv.getvrf()));
pst.setString(5,convertNullToEmptyString(srv.getaddress()));
pst.executeUpdate();
Thank you for help
The error is:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'SELECT DISTINCT '20' FROM dual WHERE NOT EXISTS(SELECT * FROM tout
WHERE 'VLAN'=' at line 1
It's either insert into ... values(...) or insert into ... select ..., you can't use both in the same statement.

Categories