I installed a Derby DB and I opened a connection named "MyDbTest".
I created a table named BOOK for "MyDbTest" connection by the SQL command:
CREATE TABLE BOOK(ID INT, DESCRIPTION VARCHAR(20), UNITCOST VARCHAR(20), ISBN VARCHAR(20), NBOFPAGES INT);
I ran the Derby server by using the command: "startNetworkServer.bat"
I ran the following code (using Open JPA):
public class Main {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.println("\n\n>>> Executing : " + Main.class.toString() + " <<<\n");
persistBook(new Book(new Long(5000), "H2G2", "Best IT Scifi Book", new Float(12.5), "1234-5678-5678",
new Integer(247)));
Book book = findBook(new Long(5000));
System.out.println("# " + book);
}
/**
* Gets a database connection
*/
static {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:derby://localhost:1527/MyDbTest;create=true", "app", "app");
}
/**
* Persists the book to the database
*/
private static void persistBook(Book book) throws SQLException {
String query = "INSERT INTO BOOK (ID, TITLE, DESCRIPTION, UNITCOST, ISBN, NBOFPAGE) VALUES (?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = getConnection().prepareStatement(query)) {
stmt.setLong(1, book.getId().longValue());
stmt.setString(2, book.getTitle());
stmt.setString(3, book.getDescription());
stmt.setFloat(4, book.getUnitCost().longValue());
stmt.setString(5, book.getIsbn());
stmt.setInt(6, book.getNbOfPage().intValue());
stmt.executeUpdate();
}
}
}
and I got an Error:
Exception in thread "main" java.sql.SQLSyntaxErrorException:
Table/View 'BOOK' does not exist.
Caused by: ERROR 42X05: Table/View 'BOOK' does not exist.
I also read the solution proposed in this post: Is it necessary to create tables each time you connect the derby database?.
Unfortunately, none of them helped me.
I changed "jdbc:derby://localhost:1527/MyDbTest;create=true" to "jdbc:derby://localhost:1527/MyDbTest;create=false"
I don't use "in-memory" configuration in Derby.
I don't think I connect to the DB as another user (I'm not sure about it. How can I check it?).
I had this error because I was using the database name in the SELECT statement instead of the name of the table.
Related
We are trying to load data to google bigquery using Jdbc (Simba driver). When trying to insert a null value in a prepared statement, we are getting an exception. This works when it is not a prepared statement. For example, the code (with the connection Url hidden):
import java.sql.*;
public class Program {
public static void main(String[] args) {
Program program = new Program();
try {
program.doStatement();
} catch (Exception e) {
e.printStackTrace();
}
try {
program.doPreparedStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public Program() {}
public void doPreparedStatement() throws Exception {
try(Connection connection = getConnection()) {
PreparedStatement statement = connection.prepareStatement("INSERT INTO test1.my_table (CONTACT, COMPANY, ADDRESS, CITY, STATE, ZIP) VALUES (?,?,?,?,?,?)");
statement.setString(1, "MyContact");
statement.setString(2, "MyCompany");
statement.setString(3, "MyAddress");
statement.setString(4, "MyCity");
statement.setString(5, "MyState");
statement.setNull(6, Types.BIGINT);
System.err.println("Executing prepared statement...");
int count = statement.executeUpdate();
}
System.err.println(" done.");
}
public void doStatement() throws Exception {
try(Connection connection = getConnection()) {
String create_command =
"CREATE TABLE test1.my_table ( CONTACT STRING, COMPANY STRING, ADDRESS STRING, CITY STRING, STATE STRING, ZIP STRING )";
Statement createStatement = connection.createStatement( );
System.err.println("Create table.");
createStatement.execute(create_command);
System.err.println("Table created.");
System.err.println("Executing statement...");
Statement statement = connection.createStatement();
int count = statement.executeUpdate("INSERT INTO test1.my_table (CONTACT, COMPANY, ADDRESS, CITY, STATE, ZIP) VALUES ('MyContact','MyCompany','MyAddress','MyCity','MyState',NULL)");
}
System.err.println(" done.");
}
private Connection getConnection() throws Exception
{
Connection connection = null;
connection = DriverManager.getConnection(CONNECTION_URL);
return connection;
}
}
Produces the following output:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Create table.
Table created.
Executing statement...
done.
Executing prepared statement...
java.sql.SQLException: [Simba][BigQueryJDBCDriver](100032) Error executing query job. Message: Unparseable query parameter `` in type `TYPE_INT64`, Bad int64 value: null value: 'null'
at com.simba.googlebigquery.googlebigquery.client.BQClient.insertJob(Unknown Source)
at com.simba.googlebigquery.googlebigquery.client.BQClient.executeQuery(Unknown Source)
at com.simba.googlebigquery.googlebigquery.dataengine.BQAbstractExecutor.execute(Unknown Source)
at com.simba.googlebigquery.googlebigquery.dataengine.BQSQLExecutor.execute(Unknown Source)
at com.simba.googlebigquery.jdbc.common.SPreparedStatement.executeWithParams(Unknown Source)
at com.simba.googlebigquery.jdbc.common.SPreparedStatement.executeAnyUpdate(Unknown Source)
at com.simba.googlebigquery.jdbc.common.SPreparedStatement.executeUpdate(Unknown Source)
at Program.doPreparedStatement(Program.java:35)
Caused by: com.simba.googlebigquery.support.exceptions.GeneralException: [Simba][BigQueryJDBCDriver](100032) Error executing query job. Message: Unparseable query parameter `` in type `TYPE_INT64`, Bad int64 value: null value: 'null'
... 8 more
I've found this to work when adding BigQuery support to jOOQ (see e.g. #11841), for numeric types:
statement.setBigDecimal(6, null);
The BigDecimal type is the only numeric JDBC type that is not primitive. For other data types, use their respective setter if it is supported, or setString(6, null), if Simba still doesn't like NULL values for the respective type, including e.g.:
Boolean
Date
Time
If in doubt about any conversion problems (e.g. because Simba seems to bind BigDecimal as STRING, currently, at least in version 1.2.13.1016), make sure you cast the bind variable, e.g.:
CAST(? AS INT64)
I created a Java web application, in which I use the Spring JDBC Framework, in order to write my queries for the DB2 database. So far all the queries are working excellent.
I tried today to create an INSERT query for a table I have in my database. The query is really straight forword, it works as DB2 query and it looks like this:
INSERT INTO MYDB.USERSUBSCRIPTION (USERNAME, SUBSCRIPTIONDATETIME, UNSUBSCRIPTIONDATETIME)
VALUES('JamesTheBoss', '2017-07-07 07:07:07.007', null);
In my Java class I created the following methods:
private Timestamp getCurrentDateTimeInTimeStamp() {
LocalDateTime currentDateAndTime = LocalDateTime.now();
currentDateAndTime.format(DateTimeFormatter.ofPattern("yyy-MM-dd HH:MM:SS.mm")).replaceAll("T", " ");
Timestamp timestamp = Timestamp.valueOf(currentDateAndTime);
return timestamp;
}
public void insertNewUserToDatabase(String username){
Timestamp timestamp = getCurrentDateTimeInTimeStamp();
String SQL = "INSERT INTO MYDB.USERSUBSCRIPTION (USERNAME, SUBSCRIPTIONDATETIME, UNSUBSCRIPTIONDATETIME) " +
"VALUES(?, ?, ?)";
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
jdbcTemplateObject.update(SQL,new Object[] { username, timestamp, null});
}
My first query was the following:
public List<UserSubscription> getAllUserSubscriptions() throws SQLException {
String SQL = "SELECT * FROM MYDB.USERSUBSCRIPTION";
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
List<UserSubscription> userSubscription = jdbcTemplateObject.query(SQL, new UserSubscriptionMapper());
return userSubscription;
}
and it works fine, as all other queries I wrote also do.
When I try to insert "null" as a Timestamp Parameter in the query, I become an exception.
How can I insert a "null" value for a Timestamp by using the Spring JDBC Framework?
I would really appreciate having a feedback.
I have been debbuging for a while and I found out that I can hardcode a null in my query and then the query works fine.
With a hardcoded "null" the query looks like this:
public void insertNewUserToDatabase(String username){
Timestamp timestamp = getCurrentDateTimeInTimeStamp();
String SQL = "INSERT INTO MYDB.USERSUBSCRIPTION (USERNAME, SUBSCRIPTIONDATETIME, UNSUBSCRIPTIONDATETIME) " +
"VALUES(?, ?, null)"; // <--- Hard Coded "null"
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
jdbcTemplateObject.update(SQL,new Object[] { username, timestamp});
}
When this query is executed, I become a new record in DB2 Database with a "null" value for column "UNSUBSCRIPTIONDATETIME".
I'm using Spring and Oracle database in my solution and i need to execute script
select count(1) from ELEMENTS, table(cast(? as arrayofnumbers)) session_ids
where root_session_id in session_ids.VALUE
but i have a problem with passing input parameter.
i try to pass List or array of BigInteger into
JdbcTemplate.queryForObject("select count(1) from ELEMENTS, table(cast(? as arrayofnumbers)) session_ids
where root_session_id in session_ids.VALUE", Integer.class, INPUT_PARAMS)
but has an Exception:
java.sql.SQLException: Invalid column type
at oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:8861)
at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:8338)
at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:9116)
at oracle.jdbc.driver.OraclePreparedStatement.setObject(OraclePreparedStatement.java:9093)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.setObject(OraclePreparedStatementWrapper.java:234)
at weblogic.jdbc.wrapper.PreparedStatement.setObject(PreparedStatement.java:357)
Does anyone have the same problem?
EDIT:
Forget to describe arrayofnumber. It's custom type:
TYPE arrayofnumbers as table of number(20)
Found the solution:
final BigInteger[] ids = new BigInteger[]{BigInteger.valueOf(9137797712513092132L)};
int count = jdbc.query("select count(1) from NC_DATAFLOW_ELEMENTS\n" +
" where root_session_id in (select /*+ cardinality(t 10) */ * from table(cast (? as arrayofnumbers)) t)"
, new PreparedStatementSetter() {
public void setValues(PreparedStatement preparedStatement) throws SQLException {
Connection conn = preparedStatement.getConnection();
OracleConnection oraConn = conn.unwrap(OracleConnection.class);
oracle.sql.ARRAY widgets = oraConn.createARRAY("ARRAYOFNUMBERS", ids);
preparedStatement.setArray(1, widgets);
}
}, new ResultSetExtractor<Integer>() {
public Integer extractData(ResultSet resultSet) throws SQLException, DataAccessException {
resultSet.next();
return resultSet.getInt(1);
}
});
out.println(count);
should note that type of array (ARRAYOFNUMBER) should be in upper case
#Override
public List<String> getusers(String role) {
// TODO Auto-generated method stub
String namecount = "SELECT userName FROM users WHERE userName LIKE ?";
role="\"%" + role + "%\"";
List<String> names = jdbcTemplate.query("SELECT userName FROM users where userName like ?", new RowMapper() {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
return resultSet.getString(1);
}
},role);
System.out.println(names);
return names;
}
I am not understanding why I am get this error , please can one say where it went wrong
Error message:
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT userName FROM users userName like ?]; nested exception 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 'like '%blabla%'' at line 1
You forget the WHERE keyword in the JdbcTemplate query.
import java.sql.*;
public class QBreaker
{
public static void main (String[] args)
{
Connection conn = null;
String driver="sun.jdbc.odbc.JdbcOdbcDriver";
String url="jdbc:odbc:huss";
try
{
Class.forName(driver);
conn=DriverManager.getConnection(url,"sa","admin123");
System.out.println("Connection is created");
Statement db_statement=conn.createStatement();
ResultSet rs=db_statement.executeQuery("select * from Details");
while(rs.next())
{
System.out.print("ID: "+rs.getInt("Id"));
System.out.print("\tBalance: "+rs.getString("Bal"));
}
conn.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
This is my code to connect to the database.
i have created the odbc driver n followed all the required steps in dat.
but still while running the i got this exception:
Connection is created
java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'Details'.
Process completed.
There is no such table or view named Details exists. Please verify the database.
u create Data source ? , if u not created it can u go to control panel in windows then Administrative Tools then Data Sources (ODBC) .