hsqldb call procedure from java - java

I have created this procedure in hsqldb
create procedure insertarUsuario
(nombre varchar(50), apellidos varchar(50), usuariowin varchar(10),xlnet varchar(10), correo varchar(150), planta integer, telefono integer)
MODIFIES SQL DATA
BEGIN ATOMIC
INSERT INTO USUARIOS VALUES(nombre, apellidos, usuariowin, xlnet,correo,planta,telefono);
end;
from java I call this procedure
public static void main(String[] args) throws SQLException {
ConexionBBDD con = new ConexionBBDD();
String sql = "{call public.insertarUsuario(?,?,?,?,?,?,?)}";
CallableStatement cs = con.getConnection().prepareCall(sql);
cs.setString(1, "esto");
cs.setString(2, "es");
cs.setString(3, "una");
cs.setString(4, "prueba");
cs.setString(5, "insercion");
cs.setInt(6, 1);
cs.setInt(7, 2);
cs.execute();
cs.close();
con.desconexionBBDD();
}
but don't working.
`Exception in thread "main" java.sql.SQLSyntaxErrorException: user does not have sufficient privileges or object not found: INSERTARUSUARIO
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCCallableStatement.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.prepareCall(Unknown Source)
at ventanas.pruebaConexion.main(pruebaConexion.java:28)
Caused by: org.hsqldb.HsqlException: usuario no tiene privilegios suficientes o objeto no encontrado: INSERTARUSUARIO
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(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.ParserDML.compileCallStatement(Unknown Source)
at org.hsqldb.ParserCommand.compilePart(Unknown Source)
at org.hsqldb.ParserCommand.compileStatement(Unknown Source)
at org.hsqldb.Session.compileStatement(Unknown Source)
at org.hsqldb.StatementManager.compile(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 4 more`
please helpme.

The error message means the database user does not have the privileges to call the procedure. If the PUBLIC user is calling the procedure, this statement grants the privilege. For other users replace PUBLIC with the name of the user.
GRANT ALL ON insertarUsuario TO PUBLIC
When GRANT fails with "user lacks privilege or object not found", it indicates a path to a different database is being used.

Related

No current connection to Database - java.sql.SQLNonTransientConnectionException

I'm trying to create an multithreaded app (Java) in which some threads insert further rows to database. I use Embedded Derby from JDK.
This is code that concerns establishing connection to database and inserting.
public class DatabaseConnection
{
private static String dbURL = "jdbc:derby:./Database/DB;create=true;user=fafejs;password=fafejs";
private Connection conn;
private DatabaseUpdateContent duc;
private DatabaseUpdateView duv;
public synchronized void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); // load the driver
conn = DriverManager.getConnection(dbURL); // make Derby JDBC connection
duc = new DatabaseUpdateContent(conn);
duv = new DatabaseUpdateView(conn);
System.out.println(conn);
}
catch (Exception except) // TODO - obsluga
{
except.printStackTrace();
}
}
public synchronized void recreateConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
conn = DriverManager.getConnection(dbURL);
duc = new DatabaseUpdateContent(conn);
duv = new DatabaseUpdateView(conn);
System.out.println("Reconnect:" + conn);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public boolean updatePlayer(PlayerService player)
{
try
{
int ID = player.getID();
String firstName = player.getFirstName();
String lastName = player.getLastName();
Date birthdate;
if(!(player.getDate() == null))
birthdate = new java.sql.Date(player.getDate().getTime());
else
birthdate = null;
String league = newLeagueName(player.getLeagueName()).toUpperCase();
String team = player.getTeamName();
int apps = player.getApps();
int firstSquad = player.getFirstSquad();
int minutes = player.getMinutes();
int goals = player.getGoals();
int yellowCards = player.getYellowCards();
int redCards = player.getRedCards();
duc.updatePlayersTable(ID, firstName, lastName, birthdate);
duc.updateLeagueTable(league, ID, team, apps, firstSquad, minutes, goals, yellowCards, redCards);
return true;
}
catch (SQLException sqlExcept)
{
//shutdown();
sqlExcept.printStackTrace();
return false;
}
}
public synchronized void shutdown()
{
try
{
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
//System.gc();
}
catch (SQLException sqlExcept)
{
//sqlExcept.printStackTrace();
}
}
}
public void updatePlayersTable(int ID, String firstName, String lastName, Date birthdate) throws SQLException // z klasy DatabaseUpdateContent
{
PreparedStatement pstmt = conn.prepareStatement("UPDATE APP.PLAYERS SET FIRST_NAME = ?, LAST_NAME = ?, BIRTHDATE = ? WHERE ID = ?");
pstmt.setString(1,firstName);
pstmt.setString(2,lastName);
pstmt.setDate(3,birthdate);
pstmt.setInt(4,ID);
if(pstmt.executeUpdate() == 0)
{
pstmt = conn.prepareStatement("INSERT INTO APP.PLAYERS VALUES (?,?,?,?)");
pstmt.setInt(1, ID);
pstmt.setString(2, firstName);
pstmt.setString(3, lastName);
pstmt.setDate(4, birthdate);
pstmt.execute();
}
pstmt.close();
}
public void updateDB() // procedura, która zajmuje się aktualizacją zawartości bazy danych
{
DatabaseConnection database = new DatabaseConnection();
database.createConnection();
for(PlayerService player: players)
{
while(!database.updatePlayer(player))
{
database.recreateConnection();
}
}
database.shutdown();
}
On the whole, strongly most rows are inserted to appropriate table properly, but sometimes i get SQLNonTransientConnectionException:
java.sql.SQLNonTransientConnectionException: No current connection.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
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.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.noCurrentConnection(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.checkIfClosed(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.setupContextStack(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at DatabaseService.DatabaseUpdateContent.updateLeagueTable(DatabaseUpdateContent.java:39)
at DatabaseService.DatabaseConnection.updatePlayer(DatabaseConnection.java:68)
at DataService.TeamService.updateDB(TeamService.java:66)
at DataService.TeamService.getPlayers(TeamService.java:56)
at DataService.TeamService.getPlayersUrls(TeamService.java:44)
at DataService.LeagueService.getTeams(LeagueService.java:52)
at DataService.LeagueService.run(LeagueService.java:35)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR 08003: No current connection.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 17 more
java.sql.SQLException: Database './Database/DB' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
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.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at DatabaseService.DatabaseConnection.recreateConnection(DatabaseConnection.java:35)
at DataService.TeamService.updateDB(TeamService.java:69)
at DataService.TeamService.getPlayers(TeamService.java:56)
at DataService.TeamService.getPlayersUrls(TeamService.java:44)
at DataService.LeagueService.getTeams(LeagueService.java:52)
at DataService.LeagueService.run(LeagueService.java:35)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR XJ004: Database './Database/DB' not found.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 20 more
This exception occurs many times in a row, because if updating player fails, function updatePlayer will return false and we repeat loop in function updateDB. But after a while (about 50 attempts of inserting row), it's possible to establish connection and insert a row.
Certainly i've looked for solution of this problem. I tried way associated with System.gc(), what is suggested in some documentation but it doesn't help in my case.
I was considering also fact that my problem could be connected with multithreading of my app but in Embedded Derby's documentation they say in short that Embedded Derby should deal with it.
Thanks for your support in advance.
EDIT
This is error information that I get after adding code from http://wiki.apache.org/db-derby/UnwindExceptionChain:
----- SQLException -----
SQLState: 08003
Error Code: 40000
Message: No current connection.
java.sql.SQLNonTransientConnectionException: No current connection.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
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.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.noCurrentConnection(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.checkIfClosed(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.setupContextStack(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at DatabaseService.DatabaseUpdateContent.updatePlayersTable(DatabaseUpdateContent.java:17)
at DatabaseService.DatabaseConnection.updatePlayer(DatabaseConnection.java:73)
at DataService.TeamService.updateDB(TeamService.java:64)
at DataService.TeamService.getPlayers(TeamService.java:53)
at DataService.TeamService.getPlayersUrls(TeamService.java:39)
at DataService.LeagueService.getTeams(LeagueService.java:50)
at DataService.LeagueService.run(LeagueService.java:36)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR 08003: No current connection.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 17 more
java.sql.SQLException: Database './Database/DB' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
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.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at DatabaseService.DatabaseConnection.recreateConnection(DatabaseConnection.java:39)
at DataService.TeamService.updateDB(TeamService.java:67)
at DataService.TeamService.getPlayers(TeamService.java:53)
at DataService.TeamService.getPlayersUrls(TeamService.java:39)
at DataService.LeagueService.getTeams(LeagueService.java:50)
at DataService.LeagueService.run(LeagueService.java:36)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR XJ004: Database './Database/DB' not found.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 20 more
It seems to me that error associated with not finding database (to be more precise, I mean problem connected with loading the driver of Embedded Derby) is caused by SQLNonTransientConnectionException and there is the rub.

Error when adding an artist (person) in Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm creating a software in Java which should be able to register artists, Albums and Tracks as well.
Everything is connected to a MySQL DB, the software requires only artist name, I show you the methods I created. I'm sorry many of the names are in Spanish, but this
is for my school and I can't use too many english words. I think you can understand it
This is the class Conexión which makes the connection to the DB:
public class Conexion {
Connection conexion=null;
/*Conectamos a la Base de Datos*/
public Conexion(){
try{
Class.forName("com.mysql.jdbc.Driver");
conexion=DriverManager.getConnection("jdbc:mysql://localhost/chinook", "root", "");
}catch(Exception excepcion){
excepcion.printStackTrace();
}
}
/*Devolvemos la conexion*/
public Connection getConnection(){
return conexion;
}
/*Cerramos la conexión a la Base de Datos*/
public void desconectar(){
try{
conexion.close();
}catch(Exception excepcion){
excepcion.printStackTrace();
}
}
}
This is the class Coordinador, this class is used to make the union among different classes (following model MVC), I paste you the part from adding the artist, the others are just related to views:
public void addArtista(ArtistaVO artistaVO){
miLogica.validarRegistroArtista(artistaVO);
}
The class ArtistaVO where I create get and set of the artist:
public class ArtistaVO {
private int idArtista;
private String nombreArtista;
public int getIdArtista(){
return idArtista;
}
public void setIdArtista(int idArtista){
this.idArtista=idArtista;
}
public String getNombreArtista(){
return nombreArtista;
}
public void setNombreArtista(String nombreArtista){
this.nombreArtista=nombreArtista;
}
}
Method to register the artist:
public void addArtista(ArtistaVO artistaVO){
Conexion conexion=new Conexion();
try{
//Insertamos los datos del Artista
PreparedStatement sqlAddArtist=conexion.getConnection().prepareStatement("INSERT into artist values(?,?)");
ResultSet resultado=sqlAddArtist.executeQuery();
while(resultado.next()){
sqlAddArtist.setString(1, artistaVO.getNombreArtista());
sqlAddArtist.setInt(2, getMaxId()+1);
}
JOptionPane.showMessageDialog(null, "Se ha añadido exitosamente","Información",JOptionPane.INFORMATION_MESSAGE);
sqlAddArtist.close();
conexion.desconectar();
}catch(SQLException excepcion){
System.out.println(excepcion.getMessage());
JOptionPane.showMessageDialog(null,"No se registro", "Error", JOptionPane.ERROR_MESSAGE);
}
}
This method is used to create Artist ID:
public int getMaxId(){
int id=0;
Conexion conexion=new Conexion();
try{
Statement sqlMaxId=conexion.getConnection().createStatement();
ResultSet resultado=sqlMaxId.executeQuery("SELECT max(ArtistId) from artist");
if(resultado.next()){
id=resultado.getInt(0);
}
conexion.desconectar();
sqlMaxId.close();
}catch(SQLException excepcion){
System.out.println(excepcion.getMessage());
}
return id;
}
This belongs to the window which register the artist after clicking the button:
public void actionPerformed(ActionEvent evento) {
if(evento.getSource()==botonAñadir){
try{
ArtistaVO artistaVO=new ArtistaVO();
artistaVO.setNombreArtista(campoTextoArtista.getText());
miCoordinador.addArtista(artistaVO);
}catch(Exception excepcion){
JOptionPane.showMessageDialog(null, "Error al añadir Artista", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
The error I get is Error al añadir Artista (Error adding Artist), I don't know where the failure can be.
This is the exception I get:
java.lang.NullPointerException
at controlador.Coordinador.addArtista(Coordinador.java:108)
at vista.VistaArtistasAdd.actionPerformed(VistaArtistasAdd.java:70)
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)
This is the method validarRegistroArtista:
public void validarRegistroArtista(ArtistaVO artistaVO){
ArtistaDAO artistaDAO;
if(artistaVO.getIdArtista()>=0){
artistaDAO=new ArtistaDAO();
artistaDAO.addArtista(artistaVO);
}else{
JOptionPane.showMessageDialog(null, "Debe de introducirse algún numero de ID", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}
You are executing the database query before binding the values
PreparedStatement sqlAddArtist=conexion.getConnection().prepareStatement("INSERT into artist values(?,?)");
ResultSet resultado=sqlAddArtist.executeQuery();
while(resultado.next()){
sqlAddArtist.setString(1, artistaVO.getNombreArtista());
sqlAddArtist.setInt(2, getMaxId()+1);
}
This should look like this:
PreparedStatement sqlAddArtist=conexion.getConnection().prepareStatement("INSERT into artist values(?,?)");
sqlAddArtist.setString(1, artistaVO.getNombreArtista());
sqlAddArtist.setInt(2, getMaxId()+1);
sqlAddArtist.execute();

Why dont my update resultset work

I got Update sql that doesn't work, and i can't seem to make it work. I have no idea where it goes wrong, I get i Nullpointer exception.
this is my KaldSQL class
public ResultSet opdatereOrdre(Connection con, int BestillingsID, int Modtager){
ResultSet opdatereOrdre = null;
try {
PreparedStatement stmt = con.prepareStatement("UPDATE varebestillinger set BestillingsStatus=1, ModtagetAf ="+Modtager+" where BestillingsID="+BestillingsID);
opdatereOrdre = stmt.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return opdatereOrdre;
}
this is my HentbestillingsordreHandler
public void actionPerformed(ActionEvent e) {
System.out.println(hentordregistrer.BestillingsID);
try {
con = ks.connectNow();
ResultSet rs = ks.opdatereOrdre(con, hentordregistrer.BestillingsID, 1);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
the error i get is
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.StatementImpl.checkForDml(StatementImpl.java:412)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1794)
at KaldSQL.opdatereOrdre(KaldSQL.java:126)
at HentbestillingsordreHandler$1.actionPerformed(HentbestillingsordreHandler.java:120)
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$000(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)
This doesn't look like an NPE, it looks like you need to use executeUpdate instead of executeQuery. You might try this:
...
con.createStatement();
opdatereOrdre = stmt.executeUpdate("UPDATE varebestillinger set BestillingsStatus=1, ModtagetAf ="+Modtager+" where BestillingsID="+BestillingsID);
...
There are mainly three useful methods for executing query using JDBC, here below is the explaination about all that methods and understanding that where to use that methods
1. boolean execute()
Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.
2. ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
3 . int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.

Fill textbox input in db?

I am coding a CRUD app and want to fill my textbox input into the db, but I get an exception:
Here is my method:
public void create(Produkt p) {
if(p==null) {
log.error("Erstellen von null-Objekt in DB nicht möglich");
throw new IllegalArgumentException("Erstellen von null-Objekten in der DB nicht möglich");
}
if(p.getName().length()>30) {
log.error("Produktname zu lang!");
}
PreparedStatement ps=null;
try {
ps = hsqlmanager.getConnection().prepareStatement("INSERT INTO Produkt(name, kategorie, geloescht, haltbar, preis, altersfreigabe, bild) VALUES(?, ?, ?, ?, ?, ?, ?);");
} catch (SQLException e1) {
log.error("Es konnte keine Verbindung hergestellt werden im DAOProdukt!");
e1.printStackTrace();
}
try {
//TODO
ps.setString(1, p.getName());
ps.setString(2, p.getKategorie());
ps.setBoolean(3, p.isGeloescht());
ps.setBoolean(4, p.isHaltbar());
ps.setDouble(5, p.getPreis());
ps.setBoolean(6, p.isAltersfreigabe());
ps.setString(7, p.getBild());
System.out.println(p.getName() + p.getKategorie() + p.getPreis() + p.getBild() + p.isGeloescht() + p.isGeloescht() + p.isHaltbar());
ps.execute();//here I get the Exception
ps.close();
log.info("Produkt in DB erstellt.");
}
catch (SQLException e) {
log.error("createtes Produkt konnte nicht gespeicher werden - SQLFehler: " + e.toString());
e.printStackTrace();
}
}
Here is where I fill in the textbox:
String name=textBoxes.get(0).getText();
if(name.trim().isEmpty()) {
name="NO NAME ADDED!";
} else{
name = textBoxes.get(0).getText();
}
I guess it has to do with the name, beacause the exception says something like that:
Java.sql.SQLDataException: data exception: string data, right truncation
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.execute(Unknown Source)
at dao.DAOProdukt.create(DAOProdukt.java:50)
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$200(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)
So what does that mean? The exception points to the ps.execute(); but I am using the right type? Why?

MySql Query throwing an error

I am just trying to use this as a very simple register system and i want to store the users and there passwords in my table users. Everything seems to work just fine up to the point were it actually executes the query. I believe it fails in a function called checkForDML(takes 2 parameters). Please help thank you.
//password is just censored
String dbUrl = "jdbc:mysql://localhost:3306/gim?user=root&password=*********";
String dbClass = "com.mysql.jdbc.Driver";
String query = "Select * FROM users";
String user = txtUser.getText();
String password = txtPassword.getText();
txtUser.setText("");
txtPassword.setText("");
PreparedStatement ps;
query = "INSERT INTO gim.users(name, password) VALUES(?, ?)";
try
{
Class.forName(dbClass).newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/gim", "root", "Pl4tf0rmD3v");
ps = conn.prepareStatement(query);
ps.setString(1, user);
ps.setString(2, password);
ps.executeQuery();
conn.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
The stacktrace is:
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.StatementImpl.checkForDml(StatementImpl.java:490)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2194)
at com.soe.sony.im.gui.GUI$2.actionPerformed(GUI.java:181)
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$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$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)
Use the executeUpate() method rather than the executeQuery() method for an INSERT statement: executeUpdate()
The problem is here
ps.executeQuery(); should be ps.executeUpdate();
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and
returns the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement
object, which must be an SQL INSERT, UPDATE or DELETE
statement; or an SQL statement that returns nothing, such
as a DDL statement.
Also have a look at this link
Good Luck!!!

Categories

Resources