JDBC NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I've written a code in swing in which I've inserted text in jTextFields. But when I try to insert them in my database, it gives NullPointerException after "Driver Connected". Following is my JDBC code:
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("Driver Loaded.");
conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "usname", "pass");
System.out.println("Driver Connected.");
String insert = "INSERT INTO directorsdb values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pst=conn.prepareStatement(insert);
pst.setString(1, dirname.getText());
pst.setString(2, jDateChooser1.getDate().toString());
pst.setString(3, DIN.getText());
pst.setString(4, PAN.getText());
pst.setString(5, UIN.getText());
pst.setString(6, birthplace.getText());
pst.setString(7, passportno.getText());
pst.setString(8, dlicense.getText());
pst.setString(9, nationality.getText());
pst.setString(10, occupation.getText());
pst.setString(11, occupationcompany.getText());
pst.setString(12, designation.getText());
pst.setString(13, qualification.getText());
pst.setString(14, officeadd.getText());
pst.setString(15, residentialadd.getText());
pst.setString(16, contacthome.getText());
pst.setString(17, contactwork.getText());
pst.setString(18, contactmobile.getText());
pst.setString(19, emailper.getText());
pst.setString(20, emailwork.getText());
pst.setString(21, emailother.getText());
pst.setString(22, secretaryname.getText());
pst.setString(23, secretarycontact.getText());
pst.setString(24, secretaryemail.getText());
pst.setString(25, buttonGroup1.getSelection().getActionCommand());
pst.setString(26, jDateChooser2.getDate().toString());
pst.setString(27, fathername.getText());
pst.setString(28, mothername.getText());
pst.setString(29, jDateChooser3.getDate().toString());
pst.setString(30, posiionboard.getText());
pst.setString(31, jDateChooser4.getDate().toString());
pst.setString(32, cessationreason.getText());
pst.setString(33, buttonGroup2.getSelection().getActionCommand());
pst.setString(34, buttonGroup3.getSelection().getActionCommand());
pst.setString(35, aboutd.getText());
pst.execute();
}catch(SQLException e){
System.err.println(e.fillInStackTrace());
}
catch(ClassNotFoundException ex){
System.err.println(ex);
} finally{ // != means NOT EQUAL TO
if (rs != null){
try {
rs.close();
} catch (SQLException ex) {
System.err.println(ex);
}
}
if (pst != null){
try {
pst.close();
} catch (SQLException ex) {
System.err.println(ex);
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException ex) {
System.err.println(ex);
}
}
}
Following is the Exception:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at DirectorDB.NewEntry.jButton1ActionPerformed(NewEntry.java:882)
at DirectorDB.NewEntry.access$1800(NewEntry.java:28)
at DirectorDB.NewEntry$19.actionPerformed(NewEntry.java:738)
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)

What appears at line 882 of NewEntry?
Reply...
pst.setString(2, jDateChooser1.getDate().toString())
Then I would suggest that jDateChooser1.getDate() is null.
You shouldn't be setting date fields using String, the database should be setup to use an appropriate Date/Time data type and you should try to use pst.setDate(...) instead.
This will store the Date/Time value in a manner which is easily loaded. You should note Date#toString will store the date in a format specified by the current local, making it difficult to load and parse
If you can't use an actual date value in the database, then you should be using something more like...
Date value = jDateChooser1.getDate();
pst.setString(2, value == null ? null : value.toString());
Even better, use a SimpleDateFormat to format the String value into an agreeded format

Related

Why is my database arraylist population algorithm throwing an error?

This is my populate account method which takes the values from my database columns and stores them within an arraylist of objects of the account class that i made which has fields like username and password.
The second part of the code will show if you scroll down
private ArrayList<account> populateAccount() throws SQLException{
Connection c = DatabaseUtilityClass.createNewConnection();
ArrayList<account> list = new ArrayList();
try{
String q = "Select * from LOGIN";
Statement stmt = (Statement)c.createStatement();
try(ResultSet rs= stmt.executeQuery(q)){
while(rs.next()){
account a = new account();
a.setUsername(rs.getString("USERNAME"));
a.setPassword(rs.getString("PASSWORD"));
list.add(a);
}
}
}
catch(Exception e){
e.printStackTrace();
System.out.println("err");
}
c.close();
return list;
}
This is the second part of my code which should store the arraylist of objects filled with the database info and then take user text and use a for each loop to iterate through each object checking if the username and password values are the same as the one the user entered via a jTextfield and password field. The errors are on the bottom.
private void LoginActionPerformed(java.awt.event.ActionEvent evt) {
try {
accountCheck= populateAccount();
} catch (SQLException ex) {
Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex);
}
String username = user.getText();
String password = pass.getText();
for (account a:accountCheck) {
if(a.getUsername().equals(username) && a.getPassword().equals(password)){
JPanel p = (JPanel)this.getParent();
CardLayout c = (CardLayout)p.getLayout();
c.show(p, PanelConstants.Home);
}
}
}
java.lang.UnsupportedOperationException: Not supported yet.
at boomiautomationapp.account.<init>(account.java:21)
at boomiautomationapp.LoginPage.populateAccount(LoginPage.java:50)
at boomiautomationapp.LoginPage.LoginActionPerformed(LoginPage.java:146)
at boomiautomationapp.LoginPage.access$000(LoginPage.java:28)
at boomiautomationapp.LoginPage$1.actionPerformed(LoginPage.java:94)
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)

trouble in the database and checking the database in java

I am having trouble in checking the username in the ms access database
java.sql.SQLException: No data found
here is the database connect
public class dbAccess
{
Connection conn;
ResultSet rs;
Statement s;
PreparedStatement ps;
public void doConnect()
{
try
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String login = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=E:\\File Kuliah\\Semester 7\\AOOP\\JavaApplication1\\build\\classes\\Database1.accdb";
conn = DriverManager.getConnection(login);
System.out.println("Connected");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
and here is the code that has the error
private void registerButtonActionPerformed(java.awt.event.ActionEvent evt) {
try
{
db.ps = db.conn.prepareStatement("SELECT * FROM DatabaseAOOP");
db.rs = db.ps.executeQuery();
System.out.print("1");
while(db.rs.next())
{
if(userRegis.getText().equals(db.rs.getString("username")))
{
System.out.print("3");
JOptionPane.showMessageDialog(this, "Username is already exists !");
userRegis.setText("");
passRegis.setText("");
//db.rs=null;
//db.ps=null;
break;
}
else if(userRegis.getText().isEmpty())
{
JOptionPane.showMessageDialog(this, "Please input the name");
}
else if(!userRegis.getText().equals(db.rs.getString("username")))
{
JOptionPane.showMessageDialog(this, "Searching ...");
}
else
{
System.out.print("2");
db.ps = db.conn.prepareStatement("INSERT INTO DatabaseAOOP(username,password) VALUES(?,?)");
db.s = db.conn.createStatement();
db.ps.setString(1, userRegis.getText());
db.ps.setString(2, passRegis.getText());
db.ps.executeUpdate();
JOptionPane.showMessageDialog(this, "Thank you for registering !");
userRegis.setText("");
passRegis.setText("");
break;
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println(ex);
}
}
here are the printstacktrace
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(JdbcOdbc.java:3914)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(JdbcOdbcResultSet.java:5697)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:353)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:410)
at Frame.registerButtonActionPerformed(Frame.java:277)
at Frame.access$600(Frame.java:4)
at Frame$7.actionPerformed(Frame.java:135)
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:3320)
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: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)
actually i just checked the database connected, but there is no data found
Immediately after entering the while(db.rs.next()) loop you call db.rs.getString("username"), then later in the loop you call db.rs.getString("username") again. It is the second invocation that throws the "No data found" exception.
In many cases JDBC will only let us call get... methods once per column for a given (current) row in the ResultSet. You should save the value to a String
String theUserName = db.rs.getString("username");
and then use the String variable for your (multiple) comparisons.

Jtable ArrayIndexOutOfBounds Exception -1

I have developed my system using java netbeans where inside it have a JTable. Everytime when i start my program my JTable will show all the data from my sqlite. Then when i mouseclick the data it will show the details in my JtextField. i also have a menu bar on top of it. Everything is working fine except whenever i start my system if first i did not mouse click my JTable but instead i just play around with my menu bar then i press on my jtable it will show an error. ArrayIndexOutOfBoundsEception -1. This exception will only occur if i did as mention. Apart from that if i just mouseclick it again then it will be fine. Ijust want to know how to rectify this problem
I have print stack it and below is the error:
java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Vector.elementData(Vector.java:730)
at java.util.Vector.elementAt(Vector.java:473)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:649)
at Customer.table_customerMouseClicked(Customer.java:703)
at Customer.access$500(Customer.java:23)
at Customer$6.mouseClicked(Customer.java:377)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
at java.awt.Component.processMouseEvent(Component.java:6508)
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:4501)
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)
This is my code for loading the data from my sqlite and show it in my JTextField
private void table_customerMouseClicked(java.awt.event.MouseEvent evt) {
conn=javaconnect.ConnectDB();
panel_1.setVisible(false);
txt_custname.setEditable(false);
ComboBox1.setEditable(false);
txt_proID.setEditable(false);
txt_pricePer.setEditable(false);
txt_quantity1.setEditable(false);
txt_total.setEditable(false);
txt_email.setEditable(false);
txt_company.setEditable(false);
cmd_delete.setEnabled(true);
cmd_edit.setEnabled(true);
try{
int row = table_customer.getSelectedRow();
String table_click = (table_customer.getModel().getValueAt(row, 0).toString());
String sql ="select* from Customer where CustID='"+table_click+"' ";
pst = conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
String add1 = rs.getString("Name");
txt_custname.setText(add1);
String add2 = rs.getString("Email");
txt_email.setText(add2);
String add3 = rs.getString("Company");
txt_company.setText(add3);
String add4 = rs.getString("ProductName");
ComboBox1.setSelectedItem(add4);
String add5 = rs.getString("ProID");
txt_proID.setText(add5);
String add6 = rs.getString("PricePerUnit");
txt_pricePer.setText(add6);
String add7 = rs.getString("Quantity");
txt_quantity1.setText(add7);
String add8 = rs.getString("Total");
txt_total.setText(add8);
String add9 = rs.getString("CustID");
txt_custID.setText(add9);
}
String sql1= "select * from Product where Name = '"+ComboBox1.getSelectedItem()+"'";
pst = conn.prepareStatement(sql1);
rs=pst.executeQuery();
if (rs.next()){
String add1 = rs.getString("ProID");
txt_proID.setText(add1);
String add2 = rs.getString("PricePerUnit");
txt_pricePer.setText(add2);
String add3 = rs.getString("Quantity");
txt_quantity.setText(add3);
String add4 = rs.getString("StockOut");
txt_stock.setText(add4);
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
rs.close();
pst.close();
conn.close();
}
catch(Exception e){}
}
}
Your problem occurs when your mouseClicked function is called when there is no row selected in the JTable. In this case,
row = table_customer.getSelectedRow();
will return -1 if no row is selected. After that you are doing
table_customer.getModel().getValueAt(row, 0)
which will obviously throw the ArrayIndexOutOfBoundsException exception.

Display blob image from database into jlabel

public void displayPhoto() {
rs = null;
String displaySQL = "select * from images where USERNAME ='" + temp.getUsername() + "'";
try {
con = getDBConnection();
rs = st.executeQuery(displaySQL);
while (rs.next()) {
BufferedImage im = ImageIO.read(rs.getBinaryStream("IMAGES"));
displayPhoto.setIcon(new ImageIcon(im));
}
} catch (Exception e) {
e.printStackTrace();
}
}
I'm trying to display the image from database, the image stored as longblob. it says NULLPOINTERS, I dunno what's the problem
the table has 2 columns(USERNAME,IMAGES)
images = table name,
IMAGES = Column name,
displayPhoto = JLabel
can anyone help me?
thanks in advance<3
Here is the full error message
java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:228)
at MyProfile.displayPhoto(MyProfile.java:395)
at MyProfile.<init>(MyProfile.java:195)
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)
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "obierofelix");
stmt = con.createStatement();
rs = stmt.executeQuery("select * from images");
rs.next();
BufferedImage im = ImageIO.read(rs.getBinaryStream("Image"));
BackGroundImage.setIcon(new ImageIcon(im));
} catch (Exception err) {
JOptionPane.showMessageDialog(this, err.getMessage());
}
Apply rs.next(); before the try and catch block to move the pointer to the first record in the database.

How to avoid SQLException? [duplicate]

This question already has answers here:
ResultSet.getString(1) throws java.sql.SQLException: Invalid operation at current cursor position
(5 answers)
Closed 9 years ago.
This block of code gives me SQLException when i try to equal ResultSet to a String variable. can't i get a ResultSet part into a String Variable ? or any error in the code ?
And also it doesn't select any result from the database.
Pl help !
b1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
String unm = tf1.getText().toString();
String pwd = tf2.getPassword().toString();
try{
Connection con = null;
Statement stmt = null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String cn = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=E:/userlogin.accdb";
con = DriverManager.getConnection(cn,"","");
stmt = con.createStatement();
String sql = "select position from userlogin.users where users.username ='"+unm+"' and users.pwd ='"+pwd+"' ";
ResultSet rs;
rs = stmt.executeQuery(sql);
String position;
rs.next();
position = rs.getString(1);
if (position.equals("Salesman"))
{
frame.setVisible(false);
Salesman.main(null);
}
if (rs == null)
{
JOptionPane.showOptionDialog(null,
"Incorrect Username or Password !",
"Error !",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
new String[]{"Ok", "Cancel"}, // this is the array
"default");
}
stmt.close();
}
catch (HeadlessException err) {
JOptionPane.showOptionDialog(null,
"HeadlessException !",
"Error !",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
new String[]{"Ok", "Cancel"}, // this is the array
"default");
}
catch (ClassNotFoundException err) {
JOptionPane.showOptionDialog(null,
"ClassNotFoundException !",
"Error !",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
new String[]{"Ok", "Cancel"}, // this is the array
"default");
}
catch (SQLException err) {
JOptionPane.showOptionDialog(null,
"SQLException !",
"Error !",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
new String[]{"Ok", "Cancel"}, // this is the array
"default");
}
}
});
what it says is :
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - unreported exception java.sql.SQLException; must be caught or declared to be thrown
at javaproject.JavaProject$1.actionPerformed(JavaProject.java:65)
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:713)
at java.awt.EventQueue.access$000(EventQueue.java:104)
at java.awt.EventQueue$3.run(EventQueue.java:672)
at java.awt.EventQueue$3.run(EventQueue.java:670)
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:686)
at java.awt.EventQueue$4.run(EventQueue.java:684)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:683)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - unreported exception java.sql.SQLException; must be caught or declared to be thrown
at javaproject.JavaProject$1.actionPerformed(JavaProject.java:65)
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:713)
at java.awt.EventQueue.access$000(EventQueue.java:104)
at java.awt.EventQueue$3.run(EventQueue.java:672)
at java.awt.EventQueue$3.run(EventQueue.java:670)
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:686)
at java.awt.EventQueue$4.run(EventQueue.java:684)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:683)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
BUILD SUCCESSFUL (total time: 5 seconds)
First, you don't "equal" something to a variable. You assign it. (Equal is not a verb!!)
Next, you have misread the exception. It says:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException:
Uncompilable source code - unreported exception java.sql.SQLException;
must be caught or declared to be thrown at ...
You are not "getting an SQLException". And SQLException is not "appearing".
What you actually have is a compilation error ... which you have instructed your IDE to ignore. Don't do that! Fix the compilation errors before you attempt to run your application.
And the compilation error is happening because you are calling a method or methods in your code that are declared as throwing the checked exception SQLException, but your code neither catches the exception or declares it as being thrown by the method in which this code occurs.
In this particular case, that method is actionPerformed ... which is required to conform to the signature specified in the ActionListener interface that your anonymous class is implementing. Therefore, you have to catch the exception.
Now I could give you some code to copy and paste into your program to fix it. But I think it would better if you read the Oracle Java Tutorial section on exceptions and exception handling so that you could actually understand what is going on here, and understand what you need to do to fix it.

Categories

Resources