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();
Related
I am getting this error while executing my java swing code.
How to solve this? I have found some questions similar to this but didn't got the required answers.
I am making a desktop application which will read tables from excel sheet and will update the table values in a database.
Here is the code snippet:
Main code from where I am reading and calling the database query
if (flag) {
int j=0;
String[] productArray= new String[2];
for (int i = 0; i < cr.getPhysicalNumberOfCells(); i++) {
String colKeyOrTabName = getCellValueAsString((cr
.getCell(firstCell + i)));
colKeyOrTabName=colKeyOrTabName.replaceAll(" ", "");
//colKeyOrTabName=colKeyOrTabName.replaceAll("[^a-zA-Z0-9-]", "");
productArray[j]=colKeyOrTabName;
j++;
//System.out.println(" "+ colKeyOrTabName);
}
if(!productArray[0].equalsIgnoreCase("code")){
DBConfig.insertCodes(productArray[0], productArray[1]);
}
/*Ends Here*/
rowNo++;
continue;
}
DB Code :
public class DBConfig {
private static BasicDataSource bds = null;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// logger.error("Error - " + String.valueOf(e), e);
throw new RuntimeException(
"Error setting connection with SyntBots database");
}
bds = new BasicDataSource();
// set driver class name
bds.setDriverClassName("com.mysql.jdbc.Driver");
// Define Server URL
bds.setUrl(Config.get("config.db.url"));
// Define Username
bds.setUsername(Config.get("config.db.user"));
// Define Your Password
bds.setPassword(Config.get("config.db.password"));
}
public static void insertCodes(String code, String value) {
// TODO Auto-generated method stub
Connection con = null;
Statement stmt = null;
try {
// Connection conn = null;
con = bds.getConnection();
stmt = con.createStatement();
String sql = "insert into table(code,value) value('" + code+ "','"+ value+"')";
try{
stmt.executeUpdate(sql);
}
catch(SQLException e){
if(e.getErrorCode() == MYSQL_DUPLICATE_PK ){
System.out.println("Duplicate Entry"); }
}
// con.close();
} catch (Exception e) {
//logger.error("Ignore Error - " + String.valueOf(e), e);
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
}
}
if (null != con) {
try {
con.close();
} catch (SQLException e) {
}
}
}
}
}
And here is the error(Console output) :
Button clicked
D:\DesktopApplicationInputSheet
Sample.xlsx
D:\DesktopApplicationInputSheet/Sample.xlsx
Reading sheet: 0, Name: Sheet1
i: 1
0
Display Name :-Polaris Code rowNO - 1
Display Name :-AOO1 rowNO - 2
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
at
com.dataentry.excel.MainDataEntry.readRequestTable(MainDataEntry.java:249)
at
com.dataentry.excel.MainDataEntry.readExcelandWriteonDB(MainDataEntry.java:149)
at
com.dataentry.excel.MainDataEntry.readExcelPath(MainDataEntry.java:79)
at
com.dataentry.excel.MainDataEntry$1.actionPerformed(MainDataEntry.java:57)
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: java.lang.RuntimeException: Error setting connection with SyntBots database
at com.dataentry.excel.DBConfig.<clinit>(DBConfig.java:26)
... 40 more
Update :
The Issue is fixed. It was of the case of missing JAR for MySQL driver.
But after that I am facing a new issue.
Have a look at the console output:
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: org.apache.commons.pool2.impl.GenericObjectPool.setTestOnCreate(Z)V
at org.apache.commons.dbcp2.BasicDataSource.createConnectionPool(BasicDataSource.java:2074)
at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:1920)
at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1413)
at com.dataentry.excel.DBConfig.insertCodes(DBConfig.java:59)
at com.dataentry.excel.MainDataEntry.readRequestTable(MainDataEntry.java:249)
at com.dataentry.excel.MainDataEntry.readExcelandWriteonDB(MainDataEntry.java:149)
at com.dataentry.excel.MainDataEntry.readExcelPath(MainDataEntry.java:79)
at com.dataentry.excel.MainDataEntry$1.actionPerformed(MainDataEntry.java:57)
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)
Well I have found the answer to my problem.
In my case it was related to the version of commons-pool2-2 jar file.
Instead of 2.4.2, I was using 2.0.
After changing the JAR to 2.4.2 it started working as expected.
Also I have used the mysql-connector-java-5.1.18 to resolve my previous issue.
NOTE : What I have found from the internet is that JAR compatibility is also need to fix the program.
I have been trying to execute the following query :
SQL_ADDPROJECT = "INSERT INTO project (name, description, duration, departement, chef) VALUES (?, ?, ?, ?, ?)";
using:
public boolean addProject(String name, String description, String duration, String budget, int chef, int departement) {
try {
addProject_statement = connection.prepareStatement(SQL_ADDPROJECT);
addProject_statement.setString(1, name);
addProject_statement.setString(2, description);
addProject_statement.setString(3, duration);
addProject_statement.setString(4, budget);
addProject_statement.setInt(5, chef);
addProject_statement.setInt(6, departement);
int res = addProject_statement.executeUpdate();
if ( res != 0 ) {
addProject_statement.close();
return true;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return false;
}
I call addProject this way :
save_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String description = descField.getText();
String duration = durationField.getText();
String budget = budgetField.getText();
int chef = User.userId;
int departement = User.departementId;
if(name != null && duration != null) {
if ( dao.addProject(name, description, duration, budget, chef, departement) ) {
JOptionPane.showMessageDialog(null, "Project " + name + " created successfully!");
MainMenu menu = new MainMenu();
menu.setVisible(true);
frame.dispose();
} else {
JOptionPane.showMessageDialog(null, "Please fill in the form correctly!");
}
return;
}
}
});
but everytime I try to execute i get a message dialogue that says 5
followed by another message dialogue that says Please fill in the form correctly
Knowing that i did fill it correctly!
Trace :
java.lang.ArrayIndexOutOfBoundsException: 5
at org.sqlite.core.CorePreparedStatement.batch(CorePreparedStatement.java:121)
at org.sqlite.jdbc3.JDBC3PreparedStatement.setInt(JDBC3PreparedStatement.java:324)
at database.SqlConnection.addProject(SqlConnection.java:75)
at project.addProject$4.actionPerformed(addProject.java:196)
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)
addProject_statement.setString(4, budget); has no matching argument in the SQL statement so number of values (and their type) do not match.
For
SQL_ADDPROJECT = "INSERT INTO project (name, description, duration, budget, departement, chef) VALUES (?, ?, ?, ?, ?, ?)";
Use
addProject_statement.setString(1, name);
addProject_statement.setString(2, description);
addProject_statement.setString(3, duration);
addProject_statement.setString(4, budget);
addProject_statement.setInt(5, departement);
addProject_statement.setInt(6, chef);
I believe you are adding 6 values in the addProject_statement but there are only 5 params in the Insertquery, thats what is causing the issue...
You statement isn't ordered. there's no budget and departement is before chef.
public boolean addProject(String name, String description, String duration, String budget, int chef, int departement) {
try {
addProject_statement = connection.prepareStatement(SQL_ADDPROJECT);
addProject_statement.setString(1, name);
addProject_statement.setString(2, description);
addProject_statement.setString(3, duration);
addProject_statement.setString(4, departement);
addProject_statement.setInt(5, chef);
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.
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?
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!!!