HSQL Statenment with sum in Java doesnt work - java

im using a embedded hsql database in my java programm.
I want to write a hsql statement like this:
statement.executeQuery("SELECT sum(Points) FROM Table");
At first i tried this one:
String column = "Points";
statement.executeQuery("SELECT sum(\""+column+"\") FROM \""+table+"\"");
java.sql.SQLException: Column not found: Points
Next one:
statement.executeQuery("SELECT sum(POINTS) FROM \""+table+"\"");
java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: POINTS
Next try, should never been working but only for you :-)
statement.executeQuery("SELECT sum(\'"+column+"\') FROM \""+table+"\"");
java.sql.SQLSyntaxErrorException: incompatible data type in operation
if i try this one:
statement.executeQuery("SELECT \""+column+"\" FROM \""+table+"\"");
runs perfectly
Just to show you that my column exist in my table.
This statement:
SELECT sum("Points") as test FROM "MyTable"
runs in SQuirrel Client Version 3.7
Any idea with my problem?

The same statement that works in SQuirrel should work. This is the same statement with Java quoting:
statement.executeQuery("SELECT sum(\"Points\") FROM \"MyTable\"");
It looks like you are connecting to a different database from your program and from SQuirrel. Try using the same absolute path to the database file in SQuirrel and in your program. You cannot connect at the same time, so you need to shutdown the database in SQuirrel before you connect from your program.

These are my imports
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
This Statment also not run:
statement.executeQuery("SELECT sum(\"Points\") FROM \"MyTable\"");
SOLUTION for maybe others:
"SELECT sum(\"Punkte\") as TEST FROM \"Match_Stats\"");
while(table_01.next()){
players.get(i).setPoints(table_01.getInt("TEST"));
}
Alias TEST was the key.

Related

How to load large .sql script against oracle database using JDBC

I have a sql script for oracle database:
set define off;
CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "XYZ" AS
import javax.crypto.SecretKey;
.......
import java.security.NoSuchProviderException;
public class XYZ {
.... fields
.... methods
}
/
I'm trying to execute this statement using following java code:
String createStoredProcedureSqlString = new String(Files.readAllBytes(storedProcedureSqlFile.toPath()));
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.execute(createStoredProcedureSqlString);
}
After executing this code I faced with exception message:
java.sql.SQLException: Non supported SQL92 token at position: 479
I believe that this exception occurs while script contains "{" or "}" symbols. But I don't really know how to escape them and not affect script itself.
What am I doing wrong?

JDBC SQLite ATTACH Query while using C3P0

I recently implemented C3P0 in my database testing program (i'm using it to test different queries on our data in different DB formats... sqlite, mariadb, etc). The program was initially set up using a single sustained connection to do all queries. This worked fine with SQLite as I had to do an initial ATTACH on another table. When moving to C3P0 where it is necessary to open and close the connection on every query, how can one issue an ATTACH command and have it apply to subsequent queries? In my failure I did notice that the first query after the attach it seemed to apply.
Do I really need to interlace ATTACH test as TESTDB for EVERY query???
Running into a similar issue with setCatalog() for MariaDB. I get a "No Database selected" for every subsequent query after the first.
Do I really need to interlace ATTACH test as TESTDB for EVERY query???
No. As #MarkRotteveel suggested in a comment to the question, we can use a c3p0 connection customizer to tweak each connection as it is acquired for the pool. For example, if we create the class OurSQLiteConnectionCustomizer ...
package com.example.sqlite_pooled;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.AbstractConnectionCustomizer;
public class OurSQLiteConnectionCustomizer extends AbstractConnectionCustomizer {
public void onAcquire(Connection c, String pdsIdt) throws SQLException {
try (Statement st = c.createStatement()) {
st.execute("ATTACH DATABASE 'C:/__tmp/SQLite/test.sqlite' AS test");
}
}
}
... and we tell our ComboPooledDataSource to use it ...
cpds = new ComboPooledDataSource();
cpds.setConnectionCustomizerClassName("com.example.sqlite_pooled.OurSQLiteConnectionCustomizer");
... then whenever c3p0 acquires a new SQLite connection for the pool it will automatically perform the ATTACH DATABASE for us.

Writing Web methods to Hbase

I am not from Java ,so my question may be very easy but I need clear steps how to implement.
Existing project : Webmethods connecting to Oracle Data base to fetch certain properties file and insert log information into some tables.
Problem: Many a times data base goes down and hence delays in execution.
New Requirement: We have to replace existing oracle table with Hbase. I have writen code write file into Hbase using Pig. But I really don't know how to write the real time data into Hbase.
I found using Java client or Thrift connection I can write. I need very detailed explanation. I have to submit for an Project. Please help me out.
You have knowledge of Row oriented database and Hbase is column oriented database.But we have apache Phoenix.
Apache Phoenix is a relational database layer over HBase delivered as a client-embedded JDBC driver targeting low latency queries over HBase data. Apache Phoenix takes your SQL query, compiles it into a series of HBase scans, and orchestrates the running of those scans to produce regular JDBC result sets. The table metadata is stored in an HBase table and versioned, such that snapshot queries over prior versions will automatically use the correct schema. Direct use of the HBase API, along with coprocessors and custom filters, results in performance on the order of milliseconds for small queries, or seconds for tens of millions of rows.
This can easily solve your problem.
http://phoenix.apache.org/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class test {
public static void main(String[] args) throws SQLException {
Statement stmt = null;
ResultSet rset = null;
Connection con = DriverManager.getConnection("jdbc:phoenix:[zookeeper]");
stmt = con.createStatement();
stmt.executeUpdate("create table test (mykey integer not null primary key, mycolumn varchar)");
stmt.executeUpdate("upsert into test values (1,'Hello')");
stmt.executeUpdate("upsert into test values (2,'World!')");
con.commit();
PreparedStatement statement = con.prepareStatement("select * from test");
rset = statement.executeQuery();
while (rset.next()) {
System.out.println(rset.getString("mycolumn"));
}
statement.close();
con.close();
}
}

Hibernate multiple native SQL statements

I want to run a native SQL from a file using Hibernate. The SQL can contain several statements creating the database structure (i.e. tables, constraints but no insert/update/delete statements).
Example, very simple query is below (which contains the following two SQL statements)
CREATE DATABASE test;
CREATE TABLE test.testtbl( id int(5));
I am using MySQL db, and when I run the above query I am gettng syntax error returned. When I run them one by one, its ok.
Caused by: 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
'CREATE TABLE test.testtbl( id int(5))' at line 1
The code to run the query is below (above statement is assigned to 'sql' variable):
session = sf.openSession();
session.beginTransaction();
Query qry = session.createSQLQuery(sql);
qry.executeUpdate();
session.getTransaction().commit();
Any help would be appreciated.
As others have explained
You must run these queries one by one.
The hibernate code gets translated into running one update statement on JDBC.
But you provided two update statements.
In addition,
I personally prefer to have the code that creates tables outside of the Java application, in some DB scripts.
The parameters of the method createSQLQuery is t-sql code;
t-sql code to ensure that in the mysql interface analyzer correctly.
You can try changed the sql :'CREATE TABLE testtbl(id int(5));'
by the way you can use JDBC Connection api (Don't recommend to do so)
Such as:
java.sql.Connection conn=session.connection();

JDBC connect string and Oracle synonyms

we have a Java program connecting via JDBC thin client to an Oracle 10g database.
Everything was working fine, but now the DBA wants us to connect with a different username/password, which is supposed to have access to the same tables using public synonyms.
Unfortunately the Java program no longer sees the tables (see error below when I try to do "select * from tablename").
I have tried to connect using the same username/password with Oracle SQL Developer and in this case I can run "select * from tablename" without problems.
Is there a specific Parameter I need to put in the connect string?
Many thanks!
Exception in thread "main" java.sql.SQLException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:207)
at oracle.jdbc.driver.T4CStatement.executeForDescribe(T4CStatement.java:790)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1037)
at oracle.jdbc.driver.T4CStatement.executeMaybeDescribe(T4CStatement.java:830)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1132)
at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1687)
at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1653)
Edited by: user555817 on 08-Oct-2010 04:55
You have to append Schema Name along with the table name and make it in capital letters (I dont remember if that is case-sensitive or just caps).
Example:
If there is an Employee Table in SCH1 and the synonym is created in SCH2 as Emp for SCH2.Employee, then the below statement is valid,
SELECT * FROM SCH2.emp
Where,
emp: Synonym Name
SCH2: Schema Name where this synonym is created, not the Schema Name of the actual table.

Categories