I am trying to get an autogenerated Id after performing an insert operation. I have a table called sg_InsuranceInfo, and it generates an autoIncremented id. So I need to get it. I have attached sample code for reference
try
{
String insertQuery = "INSERT INTO sg_InsuranceInfo(Patient_Name,LIC_Name) VALUES(?,?)";
PreparedStatement preparedStatement = getConnectionObject().getConnection().prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, insuranceInformation.getPatientName());
preparedStatement.setString(2, insuranceInformation.getLicName());
int noOfRowsAffected = preparedStatement.executeUpdate();
if (noOfRowsAffected != 0)
{
ResultSet resultSet = preparedStatement.getGeneratedKeys();
if(resultSet.next())
{
System.out.println(resultSet.getInt(1));
}
}
}
catch (SQLException e)
{
e.printStackTrace();
}
This is the error text
Exception in thread "AWT-EventQueue-0" java.lang.AbstractMethodError: com.inet.tds.TdsConnection.prepareStatement(Ljava/lang/String;I)Ljava/sql/PreparedStatement;
at hospitalApp.common.InsuranceObject.saveInformation(InsuranceObject.java:42)
at hospitalApp.common.InsuranceObject.updateInformationToDatabase(InsuranceObject.java:161)
at hospitalApp.common.InsuranceController.actionPerformed(InsuranceController.java:117)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6516)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6281)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4872)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:747)
at java.awt.EventQueue.access$300(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:706)
at java.awt.EventQueue$3.run(EventQueue.java:704)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:720)
at java.awt.EventQueue$4.run(EventQueue.java:718)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:717)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
AbstractMethodError.html
Thrown when an application tries to call an abstract method. Normally,
this error is caught by the compiler; this error can only occur at run
time if the definition of some class has incompatibly changed since
the currently executing method was last compiled
I suspect that you may be using different version of JDBC jar file for compiling and running your program as this happens only on runtime.
It does the job
public void saveInformation(InsuranceInformation insuranceInformation)
{
try
{
int noOfRowsAffected = getConnectionObject().getStatement().executeUpdate(
"INSERT INTO sg_InsuranceInfo(Patient_Name,LIC_Name) VALUES(" + "'" + insuranceInformation.getPatientName() + "','" + insuranceInformation.getLicName() + "'"
+ ")");
if (noOfRowsAffected != 0)
{
ResultSet autoGeneratedId = getConnectionObject().getStatement().executeQuery("SELECT SCOPE_IDENTITY()");
if(autoGeneratedId.next())
{
System.out.println(autoGeneratedId.getInt(1));
}
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
You can get further information here http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am using NetBeans IDE 8.1 and trying to delete a product using the product id in the database. But the I am getting a runtime error
java.lang.NullPointerException
at ambeysofas.Function.deleteProduct(Function.java:220)
at ambeysofas.AmbeySofas.btnDeleteProductActionPerformed(AmbeySofas.java:866)
at ambeysofas.AmbeySofas.access$500(AmbeySofas.java:19)
at ambeysofas.AmbeySofas$7.actionPerformed(AmbeySofas.java:550)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
The Line Number 220 is the Delete Query itself. Following is the code of the function deleteProduct
public boolean deleteProduct(int id){
try {
conn.createStatement();
try{
stmt.execute("DELETE FORM tbl_products WHERE product_id="+id);
b=true;
}catch(Exception e){
System.out.print(e);
e.printStackTrace();
b=false;
}
} catch (SQLException ex) {
System.out.println(ex);
Logger.getLogger(Function.class.getName()).log(Level.SEVERE, null, ex);
b=false;
}
return b;
}
The function is called from another file. the code of the part is given below:
private void btnDeleteProductActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String str = JOptionPane.showInputDialog(this, "Enter Product ID", "Prompt", JOptionPane.OK_CANCEL_OPTION);
try {
ResultSet rs1 = new Function().fetchProductByID(Integer.parseInt(str));
while (rs1.next()) {
int r = JOptionPane.showConfirmDialog(this, rs1.getString("product_name") + " | " + rs1.getString("product_type"), "Confirm Deletion of Product:" + str, JOptionPane.OK_CANCEL_OPTION);
if (r == 0) {
if (new Function().deleteProduct(Integer.parseInt(str))) {
JOptionPane.showMessageDialog(this, "Product Deleted Successfully!", "Success!", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Something Went Wrong!", "Oops!", JOptionPane.ERROR_MESSAGE);
}
}
}
} catch (Exception e) {
}
}
The code generates the exception when the delete query is executed. I'll be thankful if anyone can suggest some solution.
maybe just a miss in you query
FORM despite of FROM
Enjoy
I'm using mysql and having select fields from a gui append to my query. However, I'm getting a mysql exception for this query: String query = "INSERT INTO racebikes " + "VALUES(?,?,?)";
For testing measures I printed out the query to make sure the fields were proper which when populated read as: INSERT INTO racebikes VALUES('BMC','Switzerland',10000.0). How is this throwing an syntax exception?
Stack trace:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?,?)' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2828)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1842)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1764)
at JDBC_GUI$7.actionPerformed(JDBC_GUI.java:375)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Snippet:
public void actionPerformed(ActionEvent e) {
String query = "INSERT INTO racebikes " + "VALUES(?,?,?)";
try{
statement = connection.prepareStatement(query);
statement.setString(1, (String)bikes_combo_box.getSelectedItem());
statement.setString(2, bike_fields[0].getText());
statement.setDouble(3, Double.parseDouble(bike_fields[1].getText()));
statement.executeUpdate(query);
} catch(SQLException e1) {
e1.printStackTrace();
}
Can you try to put the three fields before VALUES
String query = "INSERT INTO racebikes (field1, field2, field3)" + "VALUES(?,?,?)";
Replace them with your actual field names.
public void displayPhoto() {
con = null;
rs = null;
PreparedStatement preparedStatement = null;
BufferedImage bufImg = null;
String displaySQL = "select * from images where USERNAME =?";
try {
con = getDBConnection();
preparedStatement = con.prepareStatement(displaySQL);
preparedStatement.setString(1, currentuser.getText().trim());
rs = preparedStatement.executeQuery();
while (rs.next()) {
InputStream in = rs.getBinaryStream("IMAGES");
bufImg = ImageIO.read(in);
displayPhoto.setIcon(new ImageIcon(bufImg));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
This is my code and it says NullPointersException.
Here is the full error message
java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:228)
at MyProfile.displayPhoto(MyProfile.java:398)
at MyProfile.<init>(MyProfile.java:197)
at Login.actionPerformed(Login.java:93)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702)
at java.awt.EventQueue$4.run(EventQueue.java:700)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
I've been doing this for a month and I still can't retrieve the image from database, sorry but I don't have any idea about ImageIO and Stream stuff,
displayPhoto = JLabel
and it was positioned using setBounds in a Container
IMAGES = column name,
images = table name,
currentuser = label with text of the user
How to do it and why do I get this error?
You should check that your IMAGES column has no null values for that user. However, the mostly likely cause is ImageIO is unable to read your stored bytes. According to the ImageIO.read() javadoc:
If no registered ImageReader claims to be able to read the resulting stream, null is returned.
The most likely cause is the IMAGE type is not one that ImageIO can handle, or it's corrupt and ImageIO can't read it. As of JDK 1.7, ImageIO by default only handles the following image types:
JPG
PNG
BMP
WBMP
GIF
If your images are a different type, you'll need to go through extra steps to read them.
While creating a connection to Access and trying to insert simple data I get the following error:
run:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javaapplication1.Authenticate.insertdata(Authenticate.java:49)
at javaapplication1.vendor.actionPerformed(vendor.java:74)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702)
at java.awt.EventQueue$4.run(EventQueue.java:700)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Here's the code snippet if anyone can help a little and look into this. The code
code compiles fine but gives an error at runtime:
package javaapplication1;
import java.sql.*;
public class Authenticate {
final String fileName = "C:/Users/darksword/Desktopdb.accdb";
Connection con = null;
Authenticate()
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
}
catch (Exception e)
{
}
finally
{
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
}
void insertdata(String Name,String Address,String ContactNumber,int y) throws SQLException
{
String str = Integer.toString(y);
//Statement st=con.createStatement();
PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("insert into product(id,VName,VAddress,VContactNumber) values(?,?,?,?)");
pstmt.setString(1, str);
pstmt.setString(1, Name);
pstmt.setString(1, Address);
pstmt.setString(1, ContactNumber);
pstmt.executeUpdate();
pstmt.close();
}
}
You're silently catching an exception when establishing the database connection which leaves con as null should an exception occur. Add
e.printStackTrace();
to the exception block.
In addition, you close your Connection immediately after assigning the variable in the constructor
con.close();
I have a method in which i am trying to save the values from text boxes into databases but sometime it give me the error
Parameter index out of range (5>number of parameter, which is 1)
and some time java.lang.nullpointerexception
I don't understand what to do, please help.
Following is the code of the method in which i try to do insert.
private void saveActionPerformed(java.awt.event.ActionEvent evt) {
try{
if (y1.getText().equals("")) {
JOptionPane.showMessageDialog( this, "Please enter hostel code","Error", JOptionPane.ERROR_MESSAGE);
return;}
else if (y2.getText().equals("")) {
JOptionPane.showMessageDialog( this, "Please enter hostel location","Error", JOptionPane.ERROR_MESSAGE);
return;}
else if (y3.getText().equals("")) {
JOptionPane.showMessageDialog( this, "Please enter hostel name","Error", JOptionPane.ERROR_MESSAGE);
return;}
else if (y4.getText().equals("")) {
JOptionPane.showMessageDialog( this, "Please enter no of rooms","Error", JOptionPane.ERROR_MESSAGE);
return;}
else if (img.getText().equals("")) {
JOptionPane.showMessageDialog( this, "Please enter hostel image","Error", JOptionPane.ERROR_MESSAGE);
return;}
String room =gender.getSelectedItem().toString();
pst.setString(5, room);
Statement stmt;
stmt= conn.createStatement();
String sql1="Select HostelName from hostels where HostelName= '" + y3.getText() + "'";
rs=stmt.executeQuery(sql1);
if(rs.next()){
JOptionPane.showMessageDialog( this, "hostel name already exists","Error", JOptionPane.ERROR_MESSAGE);
y3.setText("");
y3.requestDefaultFocus();
return;
}
String sql = "INSERT INTO hostels (`id`, `hloc`, `HostelName`, `RoomNo`, `Capacity`,`image`) VALUES (?,?,?,?,?,?)";
pst=conn.prepareStatement(sql);
//for setting values corresponding ?
pst.setInt(1,Integer.parseInt(y1.getText()));
pst.setString(2,y2.getText());
pst.setString(3,y3.getText());
pst.setInt(4,Integer.parseInt(y4.getText()));
pst.setString(6,y5.getText());
pst.setString(7,y6.getText());
pst.executeUpdate();
pst.execute();
refresh();//Update jTable After adding a new record
JOptionPane.showMessageDialog(null, "Record Successfully Saved");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Can anyone help me to get rid of this error? following is the stack trace any help now?
java.lang.NullPointerException
at Hostels.saveActionPerformed(Hostels.java:472)
at Hostels.access$700(Hostels.java:28)
at Hostels$8.actionPerformed(Hostels.java:228)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
You never actually set any values into your prepared statement. Between pst=conn.prepareStatement(sql); and pst.execute(); you need to do pst.setXXX to set up all the values corresponding to the ? in your question.
Keep in mind that the ? are indexed starting from 1, not from 0.