简体   繁体   中英

Using JButtons to execute SQL queries with JDBC

I'm writing a simple JAVA GUI to read an SQL query from a JTextFrame and execute it.

The connect and execute buttons are both JButtons, but the compiler won't compile my code because I can't append a "throws SQLException" to actionPerformed in my Listener private classes. I tried writing separate methods, but the same problem still persists. Here's an example:

public void connect() throws SQLException {
    conxn = DriverManager.getConnection(URL, Username, Password);
}
private class SelectBut implements ActionListener {  
    public void actionPerformed(ActionEvent event){
        connect();
    }
}

The compiler just throws this back at me:

TextFrame.java:123: unreported exception java.sql.SQLException; must be caught or declared to be thrown  
public void actionPerformed(ActionEvent event){connect();}}

Any suggestions?

Since SQLException are checked exception , you must re-throw or catch it.

in your case your actionPerformed method can be something like that :

public void actionPerformed(ActionEvent event){
    try{
         connect();
    }catch(SQLException e){
         e.printStackTrace();
     }
 }

Here a tutorial about Catching and Handling Exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM