I'm trying to use HyperSQL in my Java application in the following way:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Main {
static Connection conn;
static Statement stat;
public static void main(String[] args) {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver" );
} catch (Exception ex) {
System.out.println("An error occurred while loading HSQLDB JDBC driver: " + ex.getMessage());
return;
}
try {
conn = DriverManager.getConnection(
"jdbc:hsqldb:file:helper_db;sql.syntax_mys=true");
stat = conn.createStatement();
stat.executeUpdate(
"CREATE TABLE IF NOT EXISTS some_table " +
"(" +
"foo TEXT PRIMARY KEY, " +
"bar TEXT" +
");"
);
stat.executeUpdate(
"INSERT INTO some_table VALUES" +
"('foo', 'bar') " +
"ON DUPLICATE KEY UPDATE some_table = VALUES" +
"('foo', 'bar');"
);
} catch (Exception ex) {
System.out.println("An error occurred: " + ex.getMessage());
return;
}
}
}
This code gives me the following output:
An error occurred: unexpected token: ON
What am I doing wrong? How to resolve this issue?
HSQLDB does not support the ON DUPLICATE syntax (which is clearly documente in the manual).
You need to use MERGE instead assuming that there is at least one column in your values clause that is a unique key:
MERGE INTO some_table ut
USING (
VALUES
('foo', 'bar')
) AS md (foo_column, bar_column) ON (ut.foo_column = md.foo_column)
WHEN MATCHED THEN UPDATE
SET ut.bar_column = md.bar_column
WHEN NOT MATCHED THEN
INSERT (foo_column, bar_column)
VALUES (md.foo_column, md.bar_column);
Please check the manual for more details: http://hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_merge_statement
The updated version of HSQL now supports ON DUPLICATE KEY UPDATE feature of MySQL.
Refer: http://hsqldb.org/doc/guide/guide.html#coc_compatibility_mysql
Related
As part of my java application, I have to create oracle packages from java code. Sometimes, the package code might have issues and compilation might fail. However, I am unable to capture simple failures from java. So, i have to compile > 350 oracle packages from java, and if there are errors in the package, I need to inform the user to fix them. I have pasted oracle package and java code below.
CREATE OR REPLACE PACKAGE plat_test IS
FUNCTION getmsg (
p_empno IN NUMBER
) RETURN VARCHAR2;
END plat_test;
/
CREATE OR REPLACE PACKAGE BODY plat_test AS
FUNCTION getmsg (
p_empno IN NUMBER
) RETURN VARCHAR2 IS
BEG
RETURN 'sss';
END getmsg;
END plat_teest;
Compiling / running the above code in sql developer throws:
LINE/COL ERROR
--------- -------------------------------------------------------------
0/0 PL/SQL: Compilation unit analysis terminated
1/14 PLS-00201: identifier 'PLAT_TEEST' must be declared
1/14 PLS-00304: cannot compile body of 'PLAT_TEEST' without its specification
Errors: check compiler log
I want to create the above package in java and get the result. So that I can inform the user on the failure. In java I am not able to capture the errors and the program always succeeds.
How can I capture the output in java
The java code I have:
import java.sql.*;
public class NewJDBCTester {
public static void one() {
String s_sql = "CREATE OR REPLACE PACKAGE BODY plat_test AS\n" +
" FUNCTION getmsg (\n" +
" p_empno IN NUMBER\n" +
" ) RETURN VARCHAR IS\n" +
" BEG" +
" RETURN 'ret_val';\n" +
" END getmsg;\n" +
"\n" +
"END plat_test\n" +
"/";
// String s_sql ="alter table Metric_idf from ssssssss_ssst";
// System.out.println(" SQL Stmt: " + sql);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection("jdbc:oracle:thin:bhasoor/password#10.100.1.61:34171/ssssssssssdb");
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
try {
stmt.execute (s_sql);
System.out.println(" SQL Executed Successfully ");
} catch (SQLException sqe) {
System.out.println("Error Code = " + sqe.getErrorCode());
// sqe.
System.out.println("SQL state = " + sqe.getSQLState());
System.out.println("Message = " + sqe.getMessage());
System.out.println("printTrace /n");
sqe.printStackTrace();
}
}
public static void main(String[] args) throws ClassNotFoundException {
one();
}
}
You can know if an error occurs by this way:
boolean result = stmt.execute(s_sql);
System.out.println(result ? " SQL Executed Successfully " : " SQL Executed with error ");
Then, the following query give you the error:
select *
from ALL_ERRORS
where owner = 'METRICSTREAM'
and name = 'PLAT_TEST'
--and type = 'PACKAGE BODY'
order by sequence
Here, there is no SQLException because the compilation has been completed, but with some errors.
You should use try-with-resource like this to avoid memory leaks:
try ( //
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#10.100.1.61:34171/pdb", "metricstream", "password"); //
Statement stmt = conn.createStatement(); //
) {
boolean result = stmt.execute(s_sql);
System.out.println(result ? " SQL Executed Successfully " : " SQL Executed with error ");
}
catch (SQLException sqe) {
System.out.println("Error Code = " + sqe.getErrorCode());
System.out.println("SQL state = " + sqe.getSQLState());
System.out.println("Message = " + sqe.getMessage());
System.out.println("printTrace /n");
sqe.printStackTrace();
}
You could have a look at this blog from a few years ago.
You can use the libraries from Oracle SQLDeveloper or Oracle SQLcl to run scripts like you would on the command line.
https://barrymcgillin.blogspot.com/2018/04/run-your-sql-script-from-java-now.html
In your script, you can do simple sqlplus things like
Begin
my stuff;
end;
/
show errors
You can also get the errors from the executor object after it has run.
So finally I acheived this like this. Execute the create or replace package then get the errors from dba_errors...
Posting code here...
import java.sql.*;
public class NewJDBCTester {
public static void one() throws ClassNotFoundException {
String s_sql = "CREATE OR REPLACE PACKAGE BODY plat_test AS\n" +
" FUNCTION getmsg (\n" +
" p_empno IN NUMBER\n" +
" ) RETURN VARCHAR2 IS\n" +
" BEGIN\n" +
// " RETURN 'sss';\n" +
" END getmsg;\n" +
"END plat_test;\n";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
conn = DriverManager.getConnection("jdbc:oracle:thin:user/password#10.100.1.61:34171/somedb");
stmt = conn.createStatement();
System.out.println("EXECUTING QUERY");
rset = stmt.executeQuery(s_sql);
rset.close();
stmt.close();
stmt = conn.createStatement();
rset = stmt.executeQuery("SELECT line, text FROM DBA_ERRORS WHERE OWNER = 'Bhasoor' AND NAME = 'PLAT_TEST' ORDER BY SEQUENCE desc");
while (rset.next()) {
System.out.println("ERROR AT LINE ::: " + rset.getString("line"));
System.out.println("\n");
System.out.println("ERROR DETAILS::: " + rset.getString("text"));
}
} catch (SQLException sqe) {
System.out.println("Error Code = " + sqe.getErrorCode());
System.out.println("SQL state = " + sqe.getSQLState());
System.out.println("Message = " + sqe.getMessage());
System.out.println("printTrace \n");
sqe.printStackTrace();
}
}
public static void main(String[] args) throws ClassNotFoundException {
one();
}
}
I am creating a database that keeps track of Spiderman comic books. I am getting a SQLExecption at line 28:
stmt.executeUpdate(createstring);"
So I assume there is something wrong with the syntax of my SQL that is in the createstring but nothing jumps out at me.
Below is code
import java.sql.*;
import javax.swing.*;
public class SpidermanDatabase {
public static void main(String[] args)
{
String url = "jdbc:ucanaccess://c:/users/jeff/comics.accdb";
Connection con;
String createstring;
createstring = "CREATE TABLE Spider-Man (" +
"ComicName varchar(40), " +
"IssueDate varchar(40), " +
"IssueName varchar(40), " +
"MintCond varchar(40), " +
"IssueValue double(2,2), " +
"IssueNum int)";
Statement stmt;
try
{
con = DriverManager.getConnection(url, "", "");
stmt = con.createStatement();
stmt.executeUpdate(createstring);
JOptionPane.showMessageDialog(null, "Spider-Man table created", "SQL Statement Confirmation",
JOptionPane.INFORMATION_MESSAGE);
stmt.close();
con.close();
System.exit(0);
}
catch(SQLException ex)
{
System.out.println("SQLException");
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}
Image attached is full error message
It appears to me that you are using Microsoft Access database. It also appears that you are using ucanaccess JDBC driver to connect to that database.
Your problem is that you are using an illegal character in the name of the table that you are trying to create. According to Microsoft documentation, identifiers, such as database table names, cannot contain a dash (-) (also known as a hyphen) – unless you enclose the identifier in either square brackets, i.e. [], or quotation marks.
Hence you should change the SQL create table string to the following:
createstring = "CREATE TABLE [Spider-Man] (" +
"ComicName varchar(40), " +
"IssueDate varchar(40), " +
"IssueName varchar(40), " +
"MintCond varchar(40), " +
"IssueValue double, " +
"IssueNum int)";
Also note that the double data type cannot have scale and precision qualifiers. Hence I also removed the (2,2) part from the data type for column IssueValue.
Remember that after this you must always write [Spider-Man] (or "Spider-Man") as the table name in all SQL statements. Alternatively, you could replace the dash with and underscore (_) which is a legal character in an identifier and thus do away with the need for square brackets (or quotation marks), i.e. name the table Spider_Man.
EDIT
Although the above CREATE TABLE statement is valid SQL, it appears that ucanaccess JDBC driver cannot handle it. The only way I got it to work was to replace the dash with an underscore.
Here is my java code for creating the database table Spider_Man.
(Note that the below code uses try-with-resources.)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTst0 {
public static void main(String[] args) {
String url = "jdbc:ucanaccess://C:/users/jeff/comics.accdb";
String createstring = "CREATE TABLE Spider_Man (" +
"ComicName varchar(40), " +
"IssueDate varchar(40), " +
"IssueName varchar(40), " +
"MintCond varchar(40), " +
"IssueValue double, " +
"IssueNum int)";
try (Connection con = DriverManager.getConnection(url, "", "");
Statement stmt = con.createStatement()) {
stmt.executeUpdate(createstring);
System.out.println("Spider_Man table created");
}
catch (SQLException xSql) {
xSql.printStackTrace();
}
}
}
I am using eclipse for executing the java program for simple JDBC connection with MySQL with the code as follows:
package samm;
import java.sql.*;
public class Sd {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sam", "root", "1234");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from sam1");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
I am unable to execute and get the desired result but instead, I'm getting an error message as:" Prints the ASM code to generate the given class.
Usage: ASMifier [-debug] "
This line can make a problem :
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
Why because this way is used when you define the name of the attributes in your query so instead of :
select * from sam1
Your query should look like this :
select attribute1, attribute2, attribute3 from sam1
Second solution instead of defining the index of the attribute you can use your query as it is but you have to change :
rs.getInt(1)
To this :
rs.getInt("name_of_the_attribute");// for example rs.getInt("id")
i am trying to make a simple application using h2 Database. Program is working perfectly just for one time. when i am tying to insert more data, following error occurred.
org.h2.jdbc.JdbcSQLException: Database may be already in use: "C:/Users/ali/bookDB.mv.db". Possible solutions: close all other connection(s); use the server mode [90020-186]
java.lang.IllegalStateException: The file is locked: nio:C:/Users/ali/bookDB.mv.db [1.4.186/7]
Code is
package h2_basic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class H2_Basic {
public static void main(String[] args) {
try{
Class.forName("org.h2.Driver");
Connection con = DriverManager.getConnection("jdbc:h2:~/bookDB","test","test");
Statement sta = con.createStatement();
String CREATE_TABLE = "CREATE TABLE BOOKS "
+ "(bookid bigint auto_increment NOT NULL PRIMARY KEY, "
+ " booktitle VARCHAR(255), "
+ " bookauthor VARCHAR(255), "
+ " editiondate VARCHAR(255))";
sta.execute(CREATE_TABLE);
String sql = "INSERT INTO BOOKS (booktitle, bookauthor, editiondate) VALUES ('ali','ali','12')";
sta.execute(sql);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Change your JDBC URL to jdbc:h2:~/bookDB;AUTO_SERVER=TRUE, as in
DriverManager.getConnection("jdbc:h2:~/bookDB;AUTO_SERVER=TRUE","test","test");
to start H2 in Automatic Mixed Mode.
I am trying to connect to MySQL database with Java and I get the following error:
SQLException: 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 '????????????????' at line 1
I cannot understand the error and searched a lot on the web but did not found anything. This is the code I am using:
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception E)
{
System.err.println("Unable to load driver");
E.printStackTrace();
}
try
{
Connection C = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/DATABASE_NAME","USERNAME","PASSWORD");
Statement Stmt = C.createStatement();
ResultSet RS = Stmt.executeQuery("SELECT somefield FROM sometable");
while (RS.next())
{
System.out.print("\"" + RS.getString(1) + "\"");
System.out.print(" by " + RS.getString(2));
System.out.println(": " + RS.getString(3));
}
C.close();
RS.close();
Stmt.close();
}
catch (SQLException E)
{
System.out.println("SQLException: " + E.getMessage());
System.out.println("SQLState: " + E.getSQLState());
System.out.println("VendorError: " + E.getErrorCode());
}
The SQL query above is an example for the question. The one I am using works without any problem in MySQL console. In fact, even if I remove the query and the statement from the code above, I still get the same error.
Can someone help?
Thanks in advance
Most likely it's because you're using
select field from table- table is a SQL reserved word. If you want to do this query, you'll probably need to do
select field from `table`
with the word table in back ticks.