[英]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. 我正在编写一个简单的JAVA GUI,以从JTextFrame读取SQL查询并执行它。
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. 连接和执行按钮都是JButton,但是编译器不会编译我的代码,因为我无法在“侦听器”私有类中的actionPerformed后面附加“ throws SQLException”。 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. 由于SQLException是检查异常,因此必须重新抛出或捕获它。
in your case your actionPerformed method can be something like that : 在您的情况下,您的actionPerformed方法可以是这样的:
public void actionPerformed(ActionEvent event){
try{
connect();
}catch(SQLException e){
e.printStackTrace();
}
}
Here a tutorial about Catching and Handling Exception 这里是有关捕获和处理异常的教程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.