INSERT INTO giving error in Ucanaccess - java

I am trying to insert a row into a table (userGames), using Ucanaccess, and, when executing the statement, am recieving the following error:
Feb 10, 2015 8:29:02 PM db.Connect update
SEVERE: null
net.ucanaccess.jdbc.UcanaccessSQLException: unknown token:
at net.ucanaccess.jdbc.UcanaccessStatement.execute(UcanaccessStatement.java:145)
at db.Connect.update(Connect.java:42)
at db.GameScanner.searchGames(GameScanner.java:99)
at db.GameScanner.<init>(GameScanner.java:91)
at db.WelcomeGUI.scanButtonActionPerformed(WelcomeGUI.java:143)
at db.WelcomeGUI.access$000(WelcomeGUI.java:24)
at db.WelcomeGUI$1.actionPerformed(WelcomeGUI.java:105)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6527)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6292)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4883)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.sql.SQLSyntaxErrorException: unknown token:
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.execute(Unknown Source)
at net.ucanaccess.jdbc.Execute.executeWrapped(Execute.java:62)
at net.ucanaccess.jdbc.AbstractExecute.executeBase(AbstractExecute.java:138)
at net.ucanaccess.jdbc.Execute.execute(Execute.java:52)
at net.ucanaccess.jdbc.UcanaccessStatement.execute(UcanaccessStatement.java:143)
... 42 more
Caused by: org.hsqldb.HsqlException: unknown token:
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.ParserBase.read(Unknown Source)
at org.hsqldb.ParserDQL.readColumnOrFunctionExpression(Unknown Source)
at org.hsqldb.ParserDQL.XreadSimpleValueExpressionPrimary(Unknown Source)
at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
at org.hsqldb.ParserDQL.XreadValueExpression(Unknown Source)
at org.hsqldb.ParserDQL.XreadRowElementList(Unknown Source)
at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
at org.hsqldb.ParserDQL.XreadValueExpressionOrNull(Unknown Source)
at org.hsqldb.ParserDQL.XreadValueExpressionWithContext(Unknown Source)
at org.hsqldb.ParserDQL.readRow(Unknown Source)
at org.hsqldb.ParserDQL.XreadContextuallyTypedTable(Unknown Source)
at org.hsqldb.ParserDML.compileInsertStatement(Unknown Source)
at org.hsqldb.ParserCommand.compilePart(Unknown Source)
at org.hsqldb.ParserCommand.compileStatements(Unknown Source)
at org.hsqldb.Session.executeDirectStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 48 more
In my connect class, i have the following:
private Connection conn;
public Connect(String filepath) {
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
conn = DriverManager.getConnection("jdbc:ucanaccess://" + filepath + ";");
System.out.println("Connection successful");
} catch (Exception e) {
System.out.println("ERROR: " + e);
e.printStackTrace();
}
}
and the update/insert method:
public boolean update(String sql) {
boolean result = false;
try {
Statement stmt = conn.createStatement();
result = stmt.execute(sql);
} catch (SQLException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
I am sending the following SQL statement to the update method:
"INSERT INTO userGames (userID,gameID) VALUES ("+users[id]+","+games[i]+")"
I have no idea what an "unknown token" is, or what I should do to rectify the error.
I have read the guide for Ucanaccess, and they do the same thing as I am doing, as far as I can see. Both .execute and .executeUpdate throw this error, and I do not know what to do.
Thanks for any help
Riccorbypro

The error is happening because you have pasted strings into your SQL, without enclosing them in ' ' marks, so the SQL has some words in it that the database doesn't know how to interpret.
You should be using a PreparedStatement, and setting users[id] and games[i] to parameters within the PreparedStatement. This is explained fully in The Java Tutorials

What David Wallace said .....
"INSERT INTO userGames (userID,gameID) VALUES ('"+users[id]+'",'"+games[i]+"')"
The easiest way to debug this is to just print your SQL statement before you execute it.
But you really should use a PreparedStatement

Related

Java Derby Database Insert statment error "no input parameters"

I've been searching the web for days and try to fix my problem by myself, but can't seem to get it fixed:
When I try to insert "name" and "source" into my table it always keeps telling me "no input parameters" error... pls have a look on below code:
package easylauncher;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class connectDB {
static Connection c = null;
PreparedStatement pstmt;
Statement stmt;
public connectDB() {
try {
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName(driver);
c = DriverManager.getConnection("jdbc:derby:C:\\Users\\benutzer\\easy");
String insert = "INSERT into easyl(Name,Source) VALUES (?,?)";
PreparedStatement statement = c.prepareStatement(insert);
String NAME = "hallo";
String SOURCE = "naaa";
statement.setString(1, NAME);
statement.setString(2, SOURCE);
statement.executeUpdate();
String selectSQL = "SELECT * from easyl";
PreparedStatement preparedStatement = c.prepareStatement(selectSQL);
preparedStatement.setInt(1, 1001);
ResultSet rs = preparedStatement.executeQuery();
rs.beforeFirst();
while (rs.next()) {
String name = rs.getString("Name");
String source = rs.getString("Source");
System.out.println(name + source);
}
c.close();
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void close() throws SQLException {
// TODO Auto-generated method stub
c.close();
}
}
Error:
java.sql.SQLException: No input parameters.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.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.EmbedResultSet.noStateChangeException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement.setInt(Unknown Source)
at easylauncher.connectDB.<init>(connectDB.java:59)
at easylauncher.easylauncher$1.actionPerformed(easylauncher.java:148)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: ERROR 07009: No input parameters.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.GenericParameterValueSet.checkPosition(Unknown Source)
at org.apache.derby.impl.sql.GenericParameterValueSet.getParameterForSet(Unknown Source)
... 39 more
The error is relating to this sql
String selectSQL = "SELECT * from easyl";
PreparedStatement preparedStatement = c.prepareStatement(selectSQL);
preparedStatement.setInt(1,1001);
as you can see there is no query parameters or where clause
if you want all rows then simply remove
preparedStatement.setInt(1,1001);

java.sql.SQLException: SQL sentence is closed at org.hsqldb.jdbc.JDBCUtil.sqlException

I am trying to insert a new row in my HSQLDB database. I have this code:
private final String SQL_CREAR_ATLETA=" INSERT INTO ATLETA (ID_ATLETA, DNI, NOMBRE, APELLIDOS, GENERO, NACIMIENTO, CORREO, TELEFONO, CODIGOFEDERACION) VALUES (?,?,?,?,?,?,?,?,?) ";
#Override
public void crearAtleta(String dni, String nombre, String apellidos, char genero, Date nacimiento, String correo,
String telefono, String codigoFederacion) throws SQLException {
try {
con = Jdbc.getConnection();
pst = con.prepareStatement(SQL_CREAR_ATLETA);
Integer idAtleta = calcularIdAtleta(); /*this is not null , it gives the next id , for example if there are 3 athlete in the DB , will return a 4*/
pst.setString(1, String.valueOf(idAtleta)); // <- the code crash here
pst.setString(2, nombre);
pst.setString(3, apellidos);
pst.setString(4, String.valueOf(genero));
pst.setDate(5, new java.sql.Date(nacimiento.getTime()));
pst.setString(6, dni);
pst.setString(7, correo);
pst.setString(8, telefono);
pst.setString(9, codigoFederacion);
pst.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
The program crashes at the line pst.setString(1) to set the id into the sql sentence. The stackTrace is this one :
java.sql.SQLException: SQL sentence is closed
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatementBase.checkClosed(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.checkSetParameterIndex(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.setParameter(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.setString(Unknown Source)
at reestructurado.persistencia.impl.AtletasGatewayImpl.crearAtleta(AtletasGatewayImpl.java:50)
at ui.UInscripcion$1.actionPerformed(UInscripcion.java:316)
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)
Caused by: org.hsqldb.HsqlException: sentencia SQL está cerrada
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
... 43 more
I don't unserstand the problem. I tried to change the data type, but nothing seems to work. My table is this one:
Even though you haven't disclosed all relevant code, the problem is likely that you are re-using the same PreparedStatement object across different methods. You are probably querying the next player id in calcularIdAtleta() using pst, which will leave the statement closed when calcularIdAtleta() returns. You shouldn't do that. Instead, use method-local variables; they make your code easier to read and less error-prone.
Try changing your method into this instead, essentially declaring the PreparedStatement locally:
public void crearAtleta(String dni, String nombre,
String apellidos, char genero,
Date nacimiento, String correo,
String telefono, String codigoFederacion) throws SQLException {
PreparedStatement ps = null;
try {
ps = Jdbc.getConnection().prepareStatement(SQL_CREAR_ATLETA);
Integer idAtleta = calcularIdAtleta();
ps.setString(1, String.valueOf(idAtleta));
ps.setString(2, nombre);
ps.setString(3, apellidos);
ps.setString(4, String.valueOf(genero));
ps.setDate(5, new java.sql.Date(nacimiento.getTime()));
ps.setString(6, dni);
ps.setString(7, correo);
ps.setString(8, telefono);
ps.setString(9, codigoFederacion);
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (ps != null) {
ps.close();
}
}
}

Updated in a database [update ... set] java

I have a problem with my java code. When I do a database update but they don't work up . I used the three methods that I found on the internet and still they have not worked!
Help me
thank you in advance
package HLR_SERVEUR;
public class model_HLR{
public void setupdate(String[] information)
{
int imsdn_values,cins,kcs,kis;
long IMSI_values=0;
this.IMSI_values = Long.parseLong(information[0]);
this.imsdn_values = Integer.parseInt(information[1]);
this.kis = Integer.parseInt(information[2]);
this.kcs = Integer.parseInt(information[3]);
this.service = new String(information[4]);
this.nom = new String(information[5]);
this.prenom = new String(information[6]);
this.cins = Integer.parseInt(information[7]);
System.out.println(this.IMSI_values);
System.out.println(this.imsdn_values);
System.out.println(this.kis);
System.out.println(this.kcs);
System.out.println(this.service);
System.out.println(this.nom);
System.out.println(this.prenom);
System.out.println(this.cins);
try {
Class.forName("com.mysql.jdbc.Driver");
dbConnect = DriverManager.getConnection("jdbc:mysql://localhost/abonnes", "root","");
dbStatement = dbConnect.createStatement();
/*
test 1:
PreparedStatement prepareStatement = (PreparedStatement) dbConnect.prepareStatement("Update sim set ISMIDN="+this.imsdn_values +", KI="+this.kis +",KC="+this.kcs+",SERVICE='"+this.service +"',nom='"+this.nom +"',prenom='"+this.prenom +"',cin="+this.cins +" Where IMSI="+this.IMSI_value+"");
k=prepareStatement.executeUpdate();
test 2:
PreparedStatement checkDB = (PreparedStatement) dbConnect.prepareStatement( "UPDATE sim set ISMIDN= ? ,KI= ?,KC= ?,SERVICE= ?,nom= ?,prenom= ?,cin= ? Where ISMI= ? ");
checkDB.setInt(1,this.imsdn_values);
checkDB.setInt(2,this.kis);
checkDB.setInt(3,this.kcs);
checkDB.setString(4,this.service);
checkDB.setString(5,this.nom);
checkDB.setString(6,this.prenom);
checkDB.setInt(7,this.cins);
checkDB.setLong(8,this.IMSI_values);
k=checkDB.executeUpdate();
*/
/* test 3: */
dbStatement=dbConnect.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = dbStatement
.executeQuery("SELECT * FROM sim where ISMI ='"
+ this.IMSI_values + "'");
uprs.moveToInsertRow();
uprs.updateInt("ISMIDN", this.imsdn_values);
uprs.updateInt("KI", this.kis);
uprs.updateInt("KC", this.kcs);
uprs.updateString("SERVICE", this.service);
uprs.updateString("nom", this.nom);
uprs.updateString("prenom", this.prenom);
uprs.updateInt("cin", this.cins);
uprs.insertRow();
uprs.beforeFirst();
dbStatement.close();
dbConnect.close();
} catch (SQLException ex) {
Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
}
}
mai 12, 2015 12:20:55 AM HLR_SERVEUR.model_HLR setupdate
GRAVE: null
com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'ISMI' cannot be null
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3249)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1268)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1541)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1455)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1440)
at com.mysql.jdbc.UpdatableResultSet.insertRow(UpdatableResultSet.java:739)
at HLR_SERVEUR.model_HLR.setupdate(model_HLR.java:304)
at HLR_SERVEUR.AbonnePanel_Rechercher.actionPerformed(AbonnePanel_Rechercher.java:401)
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$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.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$1.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)
problems mai 12, 2015 1:42:15 AM HLR_SERVEUR.model_HLR setupdate GRAVE: null com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '216011100258963' for key 'PRIMARY
From the log that you posted as answer, column ISMI is a mandatory field for your database table, it seems like a primary key.
You need something like:
uprs.updateInt("ISMI", someValue);
to complete your new row data.
Please also note that primary key must be unique in table.

Java Prepared-Statement getGeneratedKeys() error

I used the java prepared statement in a try-with-resources statement to access a table
in the Java DB database with NetBeans 8.0 IDE. After running the executeUpdate method ,
I then runned the generated keys method to retrieve all auto generated values.
However the generated keys resultset gives a null point error. The table has
an auto generated primary key.
the code snippet is presented below.
try (Connection con = DriverManager.getConnection(host, uName, uPass)) {
con.setAutoCommit(false); //disable auto commit
try( PreparedStatement stmAlumnus = con.prepareStatement(insertSQL)) {
stmAlumnus.setInt(1, Integer.parseInt(id_TextField.getText().trim()));
stmAlumnus.setString(2, fName_TextField.getText().toUpperCase().trim());
stmAlumnus.setString(3, lName_TextField.getText().toUpperCase().trim());
stmAlumnus.setString(4, oName_TextField.getText().toUpperCase().trim());
stmAlumnus.setInt(5, year_ComboBox.getSelectedIndex());
stmAlumnus.setBoolean(6,employeedRadioButton.isSelected());
stmAlumnus.setString(7, jTitle_TextField.getText().toUpperCase().trim());
stmAlumnus.setString(8, email_TextField.getText().toUpperCase().trim());
stmAlumnus.setString(9, tel_TextField.getText().toUpperCase().trim());
stmAlumnus.executeUpdate();
ResultSet rst = stmAlumnus.getGeneratedKeys();
863
864 while(rst.next())
865 {System.out.println("this is the ID" + rst.getNString(1));}
866 } //close prepared statement
con.commit();
} //close connection
catch (SQLException ex)
{
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch(SQLException excep) {
excep.printStackTrace();
}
Logger.getLogger(MyJFrame.class.getName()).log(Level.SEVERE, null, ex);
ex.getSuppressed();
}
}
}
below is the error message from the NetBeans IDE
run:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at wa_poly.MyJFrame.insertIntoTables(MyJFrame.java:864)
at wa_poly.MyJFrame.saveButtonActionPerformed(MyJFrame.java:653)
at wa_poly.MyJFrame.access$700(MyJFrame.java:41)
at wa_poly.MyJFrame$8.actionPerformed(MyJFrame.java:524)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6527)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6292)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4883)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Suppressed: java.sql.SQLException: Cannot close a connection while a transaction is still active.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.checkForTransactionInProgress(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.close(Unknown Source)
at wa_poly.MyJFrame.insertIntoTables(MyJFrame.java:886)
... 39 more
Caused by: java.sql.SQLException: Cannot close a connection while a transaction is still active.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown
Source)
... 47 more
Is there an explanation for the error produced.
When you prepare the statement, you have to use a flag.
e.g.
ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

How can I shut down a Derby connection that has been made by another program?

I have written a test program that makes a Derby connection and creates the necessary tables if they do not exist. But once I run the programme I can't rerun it again because the exception I have brought. I think that I should add a finilize method to the current singletone class and close the connection there. Is it the solution?
But anyway I consider the possiblity of the program crash and exiting from the program in an abnormal manner. In that case how can I force to close the other instances of the connection to the database safely and make my own connection?
public class DBTest {
public static void main(String[] args) {
DBConnection.getInstance();
}
}
public class DBConnection {
private static DBConnection ourInstance = new DBConnection();
private Connection connection;
public static DBConnection getInstance() {
return ourInstance;
}
private DBConnection() {
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
String dbName="C:/Users/Puk/IdeaProjects/DerbyTest/database/Ablauf";
String connectionURL = "jdbc:derby:" + dbName + ";create=true";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
connection = DriverManager.getConnection(connectionURL);
} catch (SQLException e) {
e.printStackTrace();
}
createTables();
}
private void createTables(){
Statement s;
try {
s = connection.createStatement();
s.execute("CREATE TABLE category ( id SMALLINT NOT NULL GENERATED ALWAYS AS IDENTITY \n" +
"\t(START WITH 0, INCREMENT BY 1), title VARCHAR(100))");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
java.sql.SQLException: Failed to start database 'C:/Users/Puk/IdeaProjects/DerbyTest/database/Ablauf' with class loader sun.misc.Launcher$AppClassLoader#1830e4a7, see the next exception for details.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.seeNextException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.bootDatabase(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection40.<init>(Unknown Source)
at org.apache.derby.jdbc.Driver40.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.Driver20.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:243)
at model.DBConnection.<init>(DBConnection.java:31)
at model.DBConnection.<clinit>(DBConnection.java:12)
at test.DBTest.main(DBTest.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.sql.SQLException: Failed to start database 'C:/Users/Puk/IdeaProjects/DerbyTest/database/Ablauf' with class loader sun.misc.Launcher$AppClassLoader#1830e4a7, see the next exception for details.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 20 more
Caused by: java.sql.SQLException: Another instance of Derby may have already booted the database C:\Users\Puk\IdeaProjects\DerbyTest\database\Ablauf.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
... 17 more
Caused by: ERROR XSDB6: Another instance of Derby may have already booted the database C:\Users\Puk\IdeaProjects\DerbyTest\database\Ablauf.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.store.raw.data.BaseDataFileFactory.privGetJBMSLockOnDB(Unknown Source)
at org.apache.derby.impl.store.raw.data.BaseDataFileFactory.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.derby.impl.store.raw.data.BaseDataFileFactory.getJBMSLockOnDB(Unknown Source)
at org.apache.derby.impl.store.raw.data.BaseDataFileFactory.boot(Unknown Source)
at org.apache.derby.impl.services.monitor.BaseMonitor.boot(Unknown Source)
at org.apache.derby.impl.services.monitor.TopService.bootModule(Unknown Source)
at org.apache.derby.impl.services.monitor.BaseMonitor.startModule(Unknown Source)
at org.apache.derby.iapi.services.monitor.Monitor.bootServiceModule(Unknown Source)
at org.apache.derby.impl.store.raw.RawStore.boot(Unknown Source)
at org.apache.derby.impl.services.monitor.BaseMonitor.boot(Unknown Source)
at org.apache.derby.impl.services.monitor.TopService.bootModule(Unknown Source)
at org.apache.derby.impl.services.monitor.BaseMonitor.startModule(Unknown Source)
at org.apache.derby.iapi.services.monitor.Monitor.bootServiceModule(Unknown Source)
at org.apache.derby.impl.store.access.RAMAccessManager.boot(Unknown Source)
at org.apache.derby.impl.services.monitor.BaseMonitor.boot(Unknown Source)
at org.apache.derby.impl.services.monitor.TopService.bootModule(Unknown Source)
at org.apache.derby.impl.services.monitor.BaseMonitor.startModule(Unknown Source)
at org.apache.derby.iapi.services.monitor.Monitor.bootServiceModule(Unknown Source)
at org.apache.derby.impl.db.BasicDatabase.bootStore(Unknown Source)
at org.apache.derby.impl.db.BasicDatabase.boot(Unknown Source)
at org.apache.derby.impl.services.monitor.BaseMonitor.boot(Unknown Source)
at org.apache.derby.impl.services.monitor.TopService.bootModule(Unknown Source)
at org.apache.derby.impl.services.monitor.BaseMonitor.bootService(Unknown Source)
at org.apache.derby.impl.services.monitor.BaseMonitor.startProviderService(Unknown Source)
at org.apache.derby.impl.services.monitor.BaseMonitor.findProviderAndStartService(Unknown Source)
at org.apache.derby.impl.services.monitor.BaseMonitor.startPersistentService(Unknown Source)
at org.apache.derby.iapi.services.monitor.Monitor.startPersistentService(Unknown Source)
... 17 more
Exception in thread "main" java.lang.ExceptionInInitializerError
at test.DBTest.main(DBTest.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.lang.NullPointerException
at model.DBConnection.createTables(DBConnection.java:41)
at model.DBConnection.<init>(DBConnection.java:35)
at model.DBConnection.<clinit>(DBConnection.java:12)
... 6 more
Process finished with exit code 1
You cannot boot a db from multiple jvms at the same time. This is explained in the docs Derby Dev Guide
HTH
D

Categories