Please have a look at the following code
package normal;
//This class if s for checking the database. If the database doesn't exists, this class will create one
import java.sql.*;
public class DatabaseCheck
{
private Connection con;
public DatabaseCheck()
{
createConnection();
try
{
Statement st = con.createStatement();
st.executeQuery("select * from PhoneData");
}
catch(Exception e)
{
System.out.println(e.getLocalizedMessage());
if(e.getLocalizedMessage().equals("Schema 'SA' does not exist"))
{
try
{
PreparedStatement ps = con.prepareStatement("create table PhoneData(ids int identity constraint pkId primary key,names varchar(20),mobileNumber1 varchar(20),mobileNumber2 varchar(20),landNumber1 varchar(20),landNumber2 varchar(20),address varchar(100),category varchar(20),nickName varchar(20),email varchar(20),middleName varchar(20),lastName varchar(20),city varchar(20),country varchar(20))");
ps.execute();
PreparedStatement ps2 = con.prepareStatement("create table Emails(accountType varchar(10) constraint pk_user primary key,userName varchar(50) ,passwords varchar(50))");
ps2.execute();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
}
finally
{
closeConnection();
}
}
public void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection("jdbc:derby:PhoneBook;create=true","sa","sasasa");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void closeConnection()
{
try
{
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This class is capable of programmatically creating tables in embedded apache derby database. But, it gives the following error
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement20.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement30.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement40.<init>(Unknown Source)
at org.apache.derby.jdbc.Driver40.newEmbedPreparedStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at normal.DatabaseCheck.<init>(DatabaseCheck.java:27)
at normal.MyPhoneBookApp.main(MyPhoneBookApp.java:25)
Caused by: java.sql.SQLException: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 15 more
Caused by: ERROR 42X01: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.ParserImpl.parseStatement(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
... 9 more
When I remove the "identity" keyword from the table creation code, this work fine. But, auto generation of ID's is mandatory. Please help!
Derby has no identity column type (as documented in the manual). You need to define a generated column. For the generation definition, Derby indeed knows an identity attribute, but that's not a datatype.
So the column definition for ids should be
ids integer generated always as identity constraint pkId primary key
Note that you can also use generated by default instead of always. Then a value will only be generated if you don't specify a value for that column during insert. generated always will overwrite any value you provide.
The Apache Derby documentation indicates you can replace the identity keyword with:
NOT NULL GENERATED ALWAYS AS IDENTITY
Related
I've been scratching my head for the past few hours wondering what is wrong. I want to edit a Date/Time format on my access database and it'a just keeps on confusing me as to why I cant update it. This is my code and I will explain. . .
This is the Main class where there's a button that says update and when clicked will lead to another class called UpdateBooking_Run()
public MainInterface() {
JButton updateBookings = new JButton("UPDATE");
updateBookings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
UpdateBooking_Run ub = new UpdateBooking_Run();
ub.setVisible(true);
}
});
}
This is UpdateBooking_Run() without the textboxes only the button inside this class...As you can see from string, I converted the date to java.sql.Date
public class UpdateBooking_Run extends JFrame {
public static java.sql.Date sqldate;
public UpdateBooking_Run() {
JButton btnAdd = new JButton("UPDATE");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Integer.parseInt(yearBookings.getText().trim());
}
catch (NumberFormatException na) {
JOptionPane.showMessageDialog(null, "Please input year", "Error", JOptionPane.ERROR_MESSAGE);
}
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
String mu = monthBookings.getSelectedItem().toString();
String da = dayBookings.getSelectedItem().toString();
String ye = yearBookings.getText().trim();
String dat = ye + "/" + mu + "/" + da ;
java.util.Date date = null;
try {
date = df.parse(dat);
} catch (ParseException e) {
e.printStackTrace();
}
sqldate = new java.sql.Date(date.getTime());
try {
UpdateConn_Run uc = new UpdateConn_Run();
uc.updateDate();
}
catch (Exception en) {
en.printStackTrace();
}
}
});
}
}
As you can see in the code above, I set sqldate as static mainly because it worked with updating string on my other classes but I just cant seem to update Date. . .
Then this is the connection... Or UpdateConn_Run()
public class UpdateConn_Run {
Connection con;
Statement st;
ResultSet rs;
StringBuffer results;
String url = "jdbc:ucanaccess://C://DATABASE//DATA.accdb";
PreparedStatement ps;
public void updateBooking() {
try {
int i = 1;
UpdateBooking_Run ubr = new UpdateBooking_Run();
MainInterface mi = new MainInterface();
Date da = UpdateBooking_Run.sqldate;
con = DriverManager.getConnection(url);
//theres actually an uneditable textbox in MainInterface that shows the ID of the selected row
int id = Integer.parseInt(mi.idstringBookings);
String sql = "UPDATE bookings SET date ='"+da+"' WHERE ID ='"+id+"'";
ps = con.prepareStatement(sql);
ps.executeUpdate();
ps.close();
con.close();
if (i == 1) {
JOptionPane.showMessageDialog(null, "Database has been updated please click Refresh");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
I also seem to get the error...
net.ucanaccess.jdbc.UcanaccessSQLException: data exception: invalid datetime format
at net.ucanaccess.jdbc.UcanaccessPreparedStatement.executeUpdate(UcanaccessPreparedStatement.java:261)
at interfaceSystem.UpdateConn_Run.updateBooking(UpdateConn_Run.java:109)
at interfaceSystem.UpdateBooking_Run$2.actionPerformed(UpdateBooking_Run.java:284)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
But it still confuses me . . .
It says invalid datetime format so I went ahead and changed the format again and again. Even tried the format in MS Access the problem still persists.
Tried not putting in the date as static. I just get "null".
Can someone explain why static is used for updating databases in PreparedStatements? Still confuses me to this day... (Everyone in my class seems to be using it although I have no idea why)
I am sorry for my English. I am not a native speaker so I appreciate it if you have questions regarding grammar...
Since you're using a PreparedStatement, you should be using placeholders and your code should be as follow:
query = "UPDATE bookings SET date = ? WHERE id = ?";
preparedStatement = con.prepareStatement(query);
preparedStatement.setDate(1, da);
preparedStatement.setInt(2, id);
preparedStatement.executeUpdate();
Because you're including a Date object into a String, it will be parsed using its toString() method, and your statement will look like:
"UPDATE bookings SET date = 2000-01-12 WHERE id = 22"
I don't do Java, but your final SQL for Access must look like this:
"UPDATE bookings SET date = #2017/03/21# WHERE ID = '1'";
or, if ID is numeric:
"UPDATE bookings SET date = #2017/03/21# WHERE ID = 1";
Thus, something like:
//datestring = da formatted as "2017/03/20"
String sql = "UPDATE bookings SET date =#"+datestring+"# WHERE ID ='"+id+"'";
So I have looked several times trough the function and nothing seems wrong. I don't pass any ResultSets to the function so I really do not get what is wrong with it. But I still get an error. The code works fine, its just that the function is used quite a lot of times and errors do not look nice on the console.
void addItemToBody(String userId, MessageReceivedEvent event, int id) throws HTTP429Exception, DiscordException, MissingPermissionsException{
String sql = "SELECT ItemType FROM items WHERE ID=?";
PreparedStatement state;
try {
state = Main.conn.prepareStatement(sql);
state.setInt(1, id);
ResultSet result = state.executeQuery();
while(result.next()){
String type = result.getString("ItemType");
if(type.equals("Head")){
state.executeUpdate("UPDATE body SET headID="+id+" WHERE playerID='"+userId+"'");
}
if(type.equals("Chest")){
state.executeUpdate("UPDATE body SET chestID="+id+" WHERE playerID='"+userId+"'");
}
if(type.equals("Pants")){
state.executeUpdate("UPDATE body SET pantsID="+id+" WHERE playerID='"+userId+"'");
}
if(type.equals("Boots")){
state.executeUpdate("UPDATE body SET bootsID="+id+" WHERE playerID='"+userId+"'");
}
if(type.equals("Melee")||type.equals("Magic")||type.equals("Ranged")){
state.executeUpdate("UPDATE body SET weaponID="+id+" WHERE playerID='"+userId+"'");
}
sendMessage("Item equipped!",event);
result.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
This is the error:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6320)
at martacus.mart.bot.rpg.InventoryHandler.addItemToBody(InventoryHandler.java:143)
at martacus.mart.bot.rpg.InventoryHandler.equipItem(InventoryHandler.java:92)
at martacus.mart.bot.rpg.InventoryHandler.OnMesageEvent(InventoryHandler.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sx.blah.discord.handle.EventDispatcher.dispatch(EventDispatcher.java:104)
at sx.blah.discord.api.internal.DiscordWS.messageCreate(DiscordWS.java:323)
at sx.blah.discord.api.internal.DiscordWS.onMessage(DiscordWS.java:144)
at org.java_websocket.client.WebSocketClient.onWebsocketMessage(WebSocketClient.java:312)
at org.java_websocket.WebSocketImpl.decodeFrames(WebSocketImpl.java:368)
at org.java_websocket.WebSocketImpl.decode(WebSocketImpl.java:157)
at org.java_websocket.client.WebSocketClient.interruptableRun(WebSocketClient.java:230)
at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:188)
at java.lang.Thread.run(Unknown Source)
You shouldn't close the ResultSet while you are still looping through it
while(result.next()){
...
result.close();
}
I'm trying to connect to HSQL using java. I'm using a tutorial to work with JDBC and hibernate. It's the lynda tutorials. Anyway, here's the code below:
package com.lynda.javatraining.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
private static final String USERNAME = "dbuser";
private static final String PASSWORD = "dbpassword";
private static final String CONN_STRING =
"jdbc:hsqldb://data/explorecalifornia";
public static void main(String[] args) throws SQLException {
//Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
System.out.println("A");
System.out.println(conn == null);
System.out.println(CONN_STRING);
try {
System.out.println("B1");
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("B1-2");
System.out.println("Connected!");
} catch (SQLException e) {
System.out.println("B2");
System.err.println(e);
} finally {
System.out.println("B3");
if (conn != null) {
conn.close();
}
}
System.out.println("C");
}
}
Here's the error I'm getting:
A
true
jdbc:hsqldb://data/explorecalifornia
B1
2014-06-27T15:26:27.430-0400 SEVERE could not reopen database
org.hsqldb.HsqlException: Database lock acquisition failure: lockFile: org.hsqldb.persist.LockFile#76d682a[file =/data/explorecalifornia.lck, exists=false, locked=false, valid=false, ] method: openRAF reason: java.io.FileNotFoundException: /data/explorecalifornia.lck (No such file or directory)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.persist.LockFile.newLockFileLock(Unknown Source)
at org.hsqldb.persist.Logger.acquireLock(Unknown Source)
at org.hsqldb.persist.Logger.openPersistence(Unknown Source)
at org.hsqldb.Database.reopen(Unknown Source)
at org.hsqldb.Database.open(Unknown Source)
at org.hsqldb.DatabaseManager.getDatabase(Unknown Source)
at org.hsqldb.DatabaseManager.newSession(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at com.lynda.javatraining.db.Main.main(Main.java:24)
B2
java.sql.SQLException: Database lock acquisition failure: lockFile: org.hsqldb.persist.LockFile#76d682a[file =/data/explorecalifornia.lck, exists=false, locked=false, valid=false, ] method: openRAF reason: java.io.FileNotFoundException: /data/explorecalifornia.lck (No such file or directory)
B3
C
Can anyone tell e what I"m doing wrong? Thanks.
A database has a lock file explorecalifornia.lck that prevents communication. You should delete lock file and restart the database. This may happens from time to time when you accidentally shutdown the database or system.
See the syntax of the command used from the command line to invoke shutdown. There's also an option how to shutdown server in Java.
I'm trying to make a java desktop database application, using the derby embedded database, I'm having some issues that I can't quite fix, and I've searched (a lot) for the answers, found some, but they couldn't solve my problem, so I decided to make a question myself. I made the database on netbeans, jut like a whole bunch of tutorials teach, downloaded the derby.jar and added to the library on the project, but then when I try to insert some data in the database's table that I created is says that the table doesn't exist.
I'm pretty sure i'm missing something really stupid, but I can't figure it out by myself, so any help will be very much appreciate. I'm new to all this java database development, I had only created local databases on c#
PS: The schema is the 'APP' one, I tried using "INSERT INTO APP.PACIENTE (ID, NOME) VALUES (1, 'victor')" but that didn't work either
public class BancoDados {
private static String url = "jdbc:derby:MeuBancoDados;create=true";
private static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
static Connection conn;
static Statement sta;
public static void insert() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
conn = null;
sta = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url);
sta = conn.createStatement();
sta.executeUpdate("INSERT INTO PACIENTE (ID, NOME) VALUES (1, 'victor')");
sta.close();
conn.close();
System.out.println("Inserido com sucesso!");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
}
}
I get This error:
Exception in thread "main" ERROR 42X05: Table 'PACIENTE' does not exist.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.DMLModStatementNode.verifyTargetTable(Unknown Source)
at org.apache.derby.impl.sql.compile.InsertNode.bind(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.executeUpdate(Unknown Source)
at projcad.BancoDados.insert(BancoDados.java:31)
at projcad.projcad.main(projcad.java:8)
Java Result: 1
Table 'PACIENTE' does not exist.
This is because in database you have not created the PACIENTE table.
Create it.
Here is my code:
package dsnless;
import java.sql.*;
////////////////////////////////////////////////////////////
//This class will be used to fire queries to the database
////////////////////////////////////////////////////////////
public class Query {
public Query(){
String pathToDatabase = "E:/Eclipse Projects/JDBC/src/datasouce/School.mdb";
String database = "jdbc:odbc:Driver="+
"{Microsoft Access Driver(*.mdb,*.accdb)};" +
":DBQ=" + pathToDatabase;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(database);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
new Query();
}
Connection con;
Statement s;
ResultSet r;
}//class Query end
Here is the exception:
java.sql.SQLException: [Microsoft][ODBC Driver Manager] DRIVER keyword syntax error
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at dsnless.Query.<init>(Query.java:14)
at dsnless.Query.main(Query.java:20)
And there is a new exception, too:
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at dsnless.Query.<init>(Query.java:14)
at dsnless.Query.main(Query.java:20)
Question
Please tell me what is wrong. I suspect it is the String database but stil it is only a guess.
Nailed it, myself
I changed the extensions supported from (*.mdb,*.accdb) to only (*.mdb) and it worked. Any idea as to why that happened???
You have an additional colon here, remove it
String database = "jdbc:odbc:Driver="+
"{Microsoft Access Driver(*.mdb,*.accdb)};" +
":DBQ=" + pathToDatabase;
^