H2 : Column not found when name has number in it - java

I have a column in my database table named '1GNics'. I can create the table in H2 using the following SQL
CREATE TABLE resource( ... 1GNics int DEFAULT NULL, ... );
This creates the table with the correct column name but if i try do a select it takes the select statement as follows and tries to select the top 1 from the table
SELECT 1 GNics from RESOURCE;
Even do the select statement reads
SELECT 1GNics from RESOURCE;
I am using hibernate to access the database so it is generating the select statements automatically. Is there a way of selecting this without changing the column name to 'oneGNics' ?

You can use HQL and use query as follows
session.createQuery("SELECT \"1GNics\" from RESOURCE");

Here is the query:
SELECT r.1GNics from RESOURCE AS r;
You can use alias of Table.

Related

Selecting default value SQL management studio

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.

Delete from table on same select same table mariadb using jpa

I need delete from table on operation of same table .JPA query is
DELETE FROM com.model.ElectricityLedgerEntity a
Where a.elLedgerid IN
(SELECT P.elLedgerid FROM
(SELECT MAX(b.elLedgerid)
FROM com.model.ElectricityLedgerEntity b
WHERE b.accountId='24' and b.ledgerType='Electricity Ledger' and b.postType='ARREARS') P );
I got this error:
with root cause org.hibernate.hql.ast.QuerySyntaxException: unexpected
token: ( near line 1, column 109 [DELETE FROM
com.bcits.bfm.model.ElectricityLedgerEntity a Where a.elLedgerid IN (
SELECT P.elLedgerid FROM ( SELECT MAX(b.elLedgerid) FROM
com.bcits.ElectricityLedgerEntity b WHERE b.accountId='24'
and b.ledgerType='Electricity Ledger' and b.postType='ARREARS') P ) ]
at
org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at
org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at
org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82)
at
org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:284)
Same query is running on mysql terminal ,but this is not working with jpa .Can any one tell me how i can write this query using jpa .
I don't understand why do you use Pbefore the last parenthesis...
The following code is not enough ?
DELETE FROM com.model.ElectricityLedgerEntity a
Where a.elLedgerid IN
(SELECT MAX(b.elLedgerid)
FROM com.model.ElectricityLedgerEntity b
WHERE b.accountId='24' and b.ledgerType='Electricity Ledger' and
b.postType='ARREARS')
Edit for bypassing mysql subquery limitations :
The new error java.sql.SQLException: You can't specify target table 'LEDGER' for update in FROM clause
is known in mysql when you use it with JPA. It's one MySQL limitation.
A recent stackoverflow question about it
In brief, you cannot "directly" updated/deleted a table that you query in a select clause
Now I understand why your original query did multiple subqueries seemingly not necessary (while it was useful for mysql) and had a "special" syntax.
I don't know tricks to solve this problem in JPA (I don't use the MySQL DBMS for a long time now).
At your place, I would do two queries. The first where you select the expected max elLedgerid and the second where you could delete line(s) with the id retrieved in the previous query.
You should not have performance issues if your sql model is well designed, the sql indexes well placed and the time to access to the database is correct.
You cannot do this in a single query with Hibernate. If you want to delete the max row(s) with Hibernate you will have to do so in two steps. First, you can find the max entry, then you can delete using that value in the WHERE clause.
But the query you wrote should actually run as a raw MySQL query. So why don't you try executing that query as a raw query:
String sql = "DELETE FROM com.model.ElectricityLedgerEntity a " +
"WHERE a.elLedgerid IN (SELECT P.elLedgerid FROM " +
"(SELECT MAX(b.elLedgerid) FROM com.model.ElectricityLedgerEntity b " +
"WHERE b.accountId = :account_id AND b.ledgerType = :ledger_type AND " +
" b.postType = :post_type) P );";
Query query = session.createSQLQuery(sql);
query.setParameter("account_id", "24");
query.setParameter("ledger_type", "Electricity Ledger");
query.setParameter("post_type", "ARREARS");
Just want to extend existing answer:
In brief, you cannot "directly" updated/deleted a table that you query in a select clause
This was lifted with starting from MariaDB 10.3.1:
Same Source and Target Table
Until MariaDB 10.3.1, deleting from a table with the same source and target was not possible. From MariaDB 10.3.1, this is now possible. For example:
DELETE FROM t1 WHERE c1 IN (SELECT b.c1 FROM t1 b WHERE b.c2=0);

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

How select column names ,column data type, key column of a table in mysql

How select column names ,column data type, key column of a table in mysql by passing the table name.
I am using mysql 5.5
Pick the info you need from
SELECT *
FROM information_schema.columns
or
SELECT *
FROM information_schema.tables
Try this:
Get structure of table
DESCRIBE table;
SELECT * FROM information_schema.tables where table_name = 'table';
Get a list of the tables in your database.
SHOW TABLES;
Whole database structure
mysqldump database_name
Select database,
execute command using desc or SHOW FIELDS FROM.
Code:
`use testDB;`
``desc `testDB`.`images`;``
-- or
`SHOW FIELDS FROM images;`
See my previous answer How to show mysql table columns data type?, it solves your problem.
The results are shown in attached image file.

How to invertly select columns in sql?

If I have a SQL table with columns:
NR_A, NR_B, NR_C, NR_D, R_A, R_B, R_C
and on runtime, I add columns following the column's sequence such that the next column above would be R_D followed by R_E.
My problem is I need to reset the values of columns that starts with R_ (labeled that way to indicate that it is resettable) back to 0 each time I re-run my script . NR_ columns btw are fixed, so it is simpler to just say something like:
UPDATE table set col = 0 where column name starts with 'NR_'
I know that is not a valid SQL but I think its the best way to state my problem.
Any thoughts?
EDIT: btw, I use postgres (if that would help) and java.
SQL doesn't support dynamically named columns or tables--your options are:
statically define column references
use dynamic SQL to generate & execute the query/queries
Java PreparedStatements do not insulate you from this--they have the same issue, just in Java.
Are you sure you have to add columns during normal operations? Dynamic datamodels are most of the time a realy bad idea. You will see locking and performance problems.
If you need a dynamic datamodel, take a look at key-value storage. PostgreSQL also has the extension hstore, check the contrib.
If you don't have many columns and you don't expect the schema to change, just list them explicitly.
UPDATE table SET NR_A=0;
UPDATE table SET NR_B=0;
UPDATE table SET NR_C=0;
UPDATE table SET NR_D=0;
Otherwise, a simple php script could dynamically build and execute your query:
<?php
$db = pg_connect("host=localhost port=5432 user=postgres password=mypass dbname=mydb");
if(!$db) die("Failed to connect");
$reset_cols = ["A","B","C","D"];
foreach ($col in $reset_cols) {
$sql = "UPDATE my_table SET NR_" . $col . "=0";
pg_query($db,$sql);
}
?>
You could also lookup table's columns in Postgresql by querying the information schema columns tables, but you'll likely need to write a plpgsql function to loop over the query results (one row per table column starting with "NR_").
if you rather using sql query script, you should try to get the all column based on given tablename.
maybe you could try this query to get all column based on given tablename to use in your query.
SELECT attname FROM
pg_attribute, pg_type
WHERE typname = 'tablename' --your table name
AND attrelid = typrelid
AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')
--note that this attname is sys column
the query would return all column with given tablename except system column

Categories