tags:

views:

130

answers:

2

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?

+3  A: 

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

Nettogrof
Yep, any method that may throw an execption must be within a try/catch block or the method calling this method must re-throw it.
Vincent Briard
Since the actionPerformed method doesn't include a throws clause, you can't throw any checked exceptions in your implementation. You'll have to catch it.
duffymo
For what it's worth, the exception shouldn't be silently absorbed like this (or converted to a runtime exception) - this is a call that's going to occur on the EDT, and bringing the EDT down isn't a good idea. At minimum, display a JOptionPane dialog box with the error message.Another point to make here: The database query will almost certainly be a long running task - running that on the EDT is a bad idea. I suggest that you do a bit more reading up on developing Swing apps (SwingWorker may be a good idea here)
Kevin Day
A: 

Check this article HOW TO: SQL in JAVA for details on how to connect to SQL Server database from C#.NET database applications as well as Java database applications. It also describes how to pass embedded SQL queries (SELECT, INSERT, UPDATE, DELETE), calling stored procedures, pass parameters etc.

SNK111