While connecting one applet to an Access DB using the jdbc:ucanaccess method, I get the following error:
Firstdb.java:44: error: unreported exception SQLException;
must be caught or declared to be thrown
stmt.executeUpdate(sql);
^
The code that I used for the applet is as follows (add()
and setBounds()
are removed from init()
):
public class Firstdb extends Applet implements ActionListener {
TextField t1, t2;
Label l1;
Button b1, b2;
Connection con;
Statement stmt;
public void init() {
try {
con = DriverManager.getConnection("jdbc:ucanaccess://H:/test/db.mdb");
stmt = con.createStatement();
} catch (Exception e) {
}
}
public void actionPerformed(ActionEvent ae) {
String sql;
if (ae.getSource() == b1) {
sql = "insert into user (Uname) values(" + t1.getText() + ")";
stmt.executeUpdate(sql);
} else if (ae.getSource() == b2) {
//do something
}
}
}
Note: java version "1.8.0_141"
Why am I getting this error?
Your code has two fatal flaws:
value
is not a valid SQL keyword. It should be values
. [Fixed in subsequent edit to question.]
Also, user
is a reserved word (function name), so if you need to use it as a table name you really should enclose it in square brackets.
The proper solution to issue #2 above is to use a parameterized query, e.g.,
sql = "insert into [user] ([Uname]) values (?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, t1.getText());
ps.executeUpdate();
It is a compile error which means that you either need to surround your stmt.executeUpdate(sql);
with try-catch statement, or your method should throw an SQLException
:
public void actionPerformed(ActionEvent ae) {
try {
String sql;
if (ae.getSource() == b1) {
sql="insert into user (Uname) values("+t1.getText()+")";
stmt.executeUpdate(sql);
} else if (ae.getSource() == b2) {
//do something
}
catch (SQLException e) {
// do something
}
}
or
public void actionPerformed(ActionEvent ae) throws SQLException {
String sql;
if (ae.getSource() == b1) {
sql="insert into user (Uname) values("+t1.getText()+")";
stmt.executeUpdate(sql);
} else if (ae.getSource() == b2) {
//do something
}
}
EDIT: By the way, I don't see if you are loading or registering Oracle JDBC driver class for UCanAccess before opening the database connection:
// Step 1: Loading or registering Oracle JDBC driver class
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
} catch(ClassNotFoundException cnfex) {
System.out.println("Problem in loading or "
+ "registering MS Access JDBC driver");
cnfex.printStackTrace();
}
So do you have it or no? If no, you should add it before getting your connection:
con = DriverManager.getConnection("jdbc:ucanaccess://H:/test/db.mdb");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With