executeUpdate() throws an ArrayIndexOutOfBoundsException - java

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);

Related

ExceptionInInitializerError while inserting Excel data in a database in Java Swing

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.

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();

Sorted JTable's data refresh gives exception in java : Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException

I try to make Test code about JTable input and refresh.
Insert and delete is working well,
but if I delete or insert data after sort the table, it make's exception:
"AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException : 9>=0" ..
Here's my test code.
How do I fix it?
and.. any other advice?
public class Test extends JFrame{
private DefaultTableModel modelTest = new DefaultTableModel();
private JTable tableTest = new JTable(modelTest);
private JScrollPane paneTest = new JScrollPane(tableTest);
private JButton button1 = new JButton("pattern1");
private JButton button2 = new JButton("pattern2");
private JButton button3 = new JButton("delete");
private void compInit(){
paneTest.setBounds(0, 0,778, 300);
button1.setBounds(250, 320,80,20);
button2.setBounds(450,320,80,20);
button3.setBounds(300,400,80,20);
DefaultTableModel tmp = modelTest;
tmp.addColumn(" ");
tmp.addColumn("col1");
tmp.addColumn("col2");
tmp.addColumn("col3");
tmp.addColumn("col4");
tmp.addColumn("col5");
tmp.addColumn("col6");
tmp.addColumn("col7");
try {
tableTest.setDefaultRenderer(Class.forName("java.lang.String"), new DefaultTableCellRenderer());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
tableTest.setAutoCreateRowSorter(true);
tableTest.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tableTest.getColumnModel().getColumn(0).setPreferredWidth(20);
tableTest.getColumnModel().getColumn(1).setPreferredWidth(45);
tableTest.getColumnModel().getColumn(2).setPreferredWidth(110);
tableTest.getColumnModel().getColumn(3).setPreferredWidth(60);
tableTest.getColumnModel().getColumn(4).setPreferredWidth(100);
tableTest.getColumnModel().getColumn(5).setPreferredWidth(227);
tableTest.getColumnModel().getColumn(6).setPreferredWidth(100);
tableTest.getColumnModel().getColumn(7).setPreferredWidth(100);
tableTest.getTableHeader().setForeground(new Color(105,105,105));
this.add(button1);
this.add(button2);
this.add(button3);
this.add(paneTest);
}
private void pattern1(){
for(int i = 0;i<10;i++){
Vector rowData = new Vector<>();
rowData.add(false);
rowData.add(i+1);
rowData.add("a : " + i);
rowData.add("b : " + i);
rowData.add("c : " + i);
rowData.add("d : " + i);
rowData.add("e : " + i);
rowData.add("f : " + i);
modelTest.addRow(rowData);
}
}
private void pattern2(){
for(int i = 0;i<10;i++){
Vector rowData = new Vector<>();
rowData.add(false);
rowData.add(i+1);
rowData.add("z : " + i);
rowData.add("y : " + i);
rowData.add("x : " + i);
rowData.add("w : " + i);
rowData.add("v : " + i);
rowData.add("u : " + i);
modelTest.addRow(rowData);
}
}
private void delete(){
DefaultTableModel tmp = modelTest;
tmp.getDataVector().removeAllElements();
tableTest.repaint();
}
private void eventInit(){
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
pattern1();
}
});
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
pattern2();
}
});
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
delete();
}
});
}
public Test(){
this.setLayout(null);
this.compInit();
this.eventInit();
this.setSize(778, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] ar){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Test();
}
});
}
}
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 >= 1
at java.util.Vector.elementAt(Unknown Source)
at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
at javax.swing.table.TableRowSorter$TableRowSorterModelWrapper.getValueAt(Unknown Source)
at javax.swing.table.TableRowSorter$TableRowSorterModelWrapper.getStringValueAt(Unknown Source)
at javax.swing.DefaultRowSorter.compare(Unknown Source)
at javax.swing.DefaultRowSorter.access$100(Unknown Source)
at javax.swing.DefaultRowSorter$Row.compareTo(Unknown Source)
at javax.swing.DefaultRowSorter$Row.compareTo(Unknown Source)
at java.util.Arrays.binarySearch0(Unknown Source)
at java.util.Arrays.binarySearch(Unknown Source)
at javax.swing.DefaultRowSorter.insertInOrder(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted0(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted(Unknown Source)
at javax.swing.JTable.notifySorter(Unknown Source)
at javax.swing.JTable.sortedTableChanged(Unknown Source)
at javax.swing.JTable.tableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableRowsInserted(Unknown Source)
at javax.swing.table.DefaultTableModel.insertRow(Unknown Source)
at javax.swing.table.DefaultTableModel.addRow(Unknown Source)
at timer.Test.pattern1(Test.java:77)
at timer.Test.access$0(Test.java:66)
at timer.Test$1.actionPerformed(Test.java:106)
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)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.DefaultRowSorter.getViewToModelAsInts(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted0(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted(Unknown Source)
at javax.swing.JTable.notifySorter(Unknown Source)
at javax.swing.JTable.sortedTableChanged(Unknown Source)
at javax.swing.JTable.tableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableRowsInserted(Unknown Source)
at javax.swing.table.DefaultTableModel.insertRow(Unknown Source)
at javax.swing.table.DefaultTableModel.addRow(Unknown Source)
at timer.Test.pattern2(Test.java:92)
at timer.Test.access$1(Test.java:81)
at timer.Test$2.actionPerformed(Test.java:111)
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)
Whenever you change your model vector directly, make sure to notify the container about this. You fail to do that in the following method:
private void delete(){
DefaultTableModel tmp = modelTest;
tmp.getDataVector().removeAllElements();
tableTest.repaint();
}
After the removeAllElements() you should call tmp.fireTableDataChanged(). Something like:
private void delete(){
DefaultTableModel tmp = modelTest;
tmp.getDataVector().removeAllElements();
tmp.fireTableDataChanged();
tableTest.repaint();
}
Reason: Changes directly to the Model's underlying data vector are not automatically propagated to the View. You are changing a Vector this way, not a Model. Changes to the Model are propagated to the View. Your calls to Model.addRow() inform the View that a row was added. Your Vector.removeAllElements() call is not informed to the View so after that call View and Model are out of sync (that is, if they weren't both empty before). The call to Model.fireTableDataChanged informs the View that the whole table data in the Model has changed. After this call they are in sync again. When Model and View are out of sync, you can expect ArrayOutOfBoundException's to occur e.g. during sorting.
I also had this problem recently - a NullPointerException caused by DefaultRowSorter.getViewToModelAsInts.
The problem for me is that I was trying to directly update the GUI when an exception was thrown in SwingWorker's doInBackground() method. I found the exact solution to my particular problem here. Maybe that will help you or at least point you in the right direction as I wouldn't be surprised if your problem was because you are trying to manipulate the GUI from the wrong thread.

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