prepareStatement(String) cannot find symbol - java

Code is
import com.sun.jdi.connect.spi.Connection;
import java.beans.Statement;
import javax.swing.JOptionPane;
import org.apache.derby.iapi.sql.PreparedStatement;
import org.apache.derby.iapi.sql.ResultSet;
Connection Con = null;
Statement St = null;
ResultSet Rs = null;
private void AddMouseClicked(java.awt.event.MouseEvent evt) {
try{
Class.forName("com.mysql.jdbc.Driver");
Con = DriverManager.getConnection("jdbc:derby://localhost:1527/Inventorydb", "root", "root");
java.sql.PreparedStatement add = Con.prepareStatement("Insert into Product Table values (?, ?, ?, ?");
add.setInt(1, Integer.parseInt(ProductID.getText()));
add.setString(2, ProductName.getText());
add.setInt(3, Integer.parseInt(ProductQuantity.getText()));
add.setString(4, Brand.getSelectedItem().toString());
int row = add.executeUpdate();
JOptionPane.showMessageDialog(this, "Product Successfully Added");
Con.close();
}catch(Exception e) {
e.printStackTrace();
}
}
private static class DriverManager {
private static Connection getConnection(String jdbcderbylocalhost1527Inventorydb, String root, String root0) {
throw new UnsupportedOperationException("Not supported yet.");
}
public DriverManager() {
}
}
using Apache Netbeans IDE 15, specifically java.sql.PreparedStatement add = Con.prepareStatement("Insert into Product Table values (?, ?, ?, ?"); this line, the prepareStatement is in red and says that "cannot find symbol" and for the life of me I cannot make sense as to why.
I've added the Class.forName first, then java.sql in java.sql.Preparedstatement second,
added a class DriverManager. Now the only error is prepareStatement. Thank you in advance.

There are a number of problems with your code:
Problem #1.
import com.sun.jdi.connect.spi.Connection;
import java.beans.Statement;
import javax.swing.JOptionPane;
import org.apache.derby.iapi.sql.PreparedStatement;
import org.apache.derby.iapi.sql.ResultSet;
4 out of 5 of those imports are incorrect. It looks like you have used your IDE's "suggest correction" feature, and it has suggested inappropriate imports.
This one is particularly harmful:
import com.sun.jdi.connect.spi.Connection;
That Connection class has nothing to do with JDBC and it doesn't have a preparedStatement method. This is the cause of the "cannot find symbol" compilation error that you mentioned in the question title.
import java.beans.Statement;
This also nothing to do with JDBC ... but it doesn't look like you use it.
import org.apache.derby.iapi.sql.PreparedStatement;
import org.apache.derby.iapi.sql.ResultSet;
These are JDBC related, but they are implementation classes for Derby NOT MySQL ... and you are apparently trying to use MySQL. Even if you were using Derby, your code should be importing the java.sql.* versions of the classes.
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
Problem #2.
Class.forName("com.mysql.jdbc.Driver");
This is unnecessary. You don't need to load the driver explicitly. The DriverManager.getConnection call will load the driver class ... assuming that it is available.
Problem #3.
Con = DriverManager.getConnection(
"jdbc:derby://localhost:1527/Inventorydb", "root", "root");
That JDBC URL is for Derby. But in the previous line you are loading a MySQL driver!
Problem #4.
Con.prepareStatement("Insert into Product Table values (?, ?, ?, ?");
As noted in another answer, the SQL is incorrect. You are missing a closing ).
Problem #5.
JOptionPane.showMessageDialog(this, "Product Successfully Added");
You are not checking the result from the executeUpdate, so that message could be a lie.
Problem #6.
Con.close();
Resource leak(s).
You should also close the PreparedStatement.
The close() calls should be made from a finally block`. Or better still use try with resources.
If the try block doesn't complete, the close() at the end won't be called. If that happens, the connection created at the start won't be closed. You will eventually run out of database connections, and the application will fail.
Problem #7.
} catch(Exception e) {
e.printStackTrace();
}
Incorrect. Only catch the exceptions that you expect.
Problem #8.
There are a number of serious style errors in your code.

Related

Why set connection.setAutoCommit(false) , insert, then rollback, still insert data to database?

My environment: Windows 11 x64, Oracle database 21c Express edtion, Java /JDK 19,IntelliJ IDEA 2023.x . I have
select banner from v$version;
-- Oracle Database 21c Express Edition Release 21.0.0.0.0 - Production
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.ZoneId;
public class VyInsert {
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "system", "12345678")) {
if (connection != null) {
connection.setAutoCommit(false);
System.out.println("Connected to the database.");
String query = "insert into SYSTEM.CUSTOMER (ID, NAME, EMAIL, CREATED_DATE) values (?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, 17);
preparedStatement.setString(2, "Nguyen Thu Hang23");
preparedStatement.setString(3, "anhtrangmuathu32#gmail.com");
preparedStatement.setObject(4, LocalDate.now(ZoneId.of("America/Montreal")));
// preparedStatement.setObject(4, LocalDate.now(ZoneId.of("Asia/Ho_Chi_Minh")));
preparedStatement.executeUpdate();
// connection.commit();
//connection.setAutoCommit(true);
} else {
System.out.println("Failed to make connection.");
}
} catch (SQLException sqlException) {
System.err.format("SQL State: %s\n%s", sqlException.getSQLState(), sqlException.getMessage());
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
Why set connection.setAutoCommit(false) , insert, then rollback, still insert data to database?
Your code never calls connection.rollback(), and the Oracle JDBC driver (or Oracle itself) is one of the few out there which commit an open transaction when you close the connection. So, once your application exits the try-with-resource block, the changes made by your application have already been committed.
Know that most JDBC drivers (or DBMSes) will rollback active transactions on connection close, and Oracle is an exception in this regard.
In addition, your screenshot shows you calling rollback in an unrelated application. That rollback statement can only roll back that transaction of that application and its connection, not the transaction of an entirely different application and its connection (especially not when that connection is already closed and its transaction committed).

Insert into mysql with preparedstatement not working [duplicate]

This question already has an answer here:
MySQL update works, but not when used in PreparedStatement
(1 answer)
Closed 5 months ago.
I'm trying to insert data into my mysql table using java, but I really can't.
I'm using PreparedStatement class to do my insertion and it seems like the '?' is not beeing changed by my variable or something like that.
So follow my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.lang.Exception;
import java.time.LocalDate;
import java.time.LocalTime;
public class db{
static String driverJDBC = "com.mysql.cj.jdbc.Driver";
static String url = "jdbc:mysql://localhost/database";
static String user = "root";
static String senha = "root";
public static void InsereVin(db banco,String vin){
Connection conexao = null;
Connection con = conexao;
//String instrucaoSQL = "insert into authentication (senha) values (\"senhaMaster\");";
String instrucaoSQL = "INSERT INTO authentication(senha) VALUES(?);";
try{
System.out.println("Carregando o driver jdbc...");
Class.forName(driverJDBC);
System.out.println("Driver carregado com sucesso");
conexao = DriverManager.getConnection(url,user,senha);
PreparedStatement preparedStmt = conexao.prepareStatement(instrucaoSQL);
preparedStmt.setString(1, vin);
/*preparedStmt.setInt (2, contador);
preparedStmt.setDate (3, java.sql.Date.valueOf(date));
preparedStmt.setTime (4, java.sql.Time.valueOf(time));
preparedStmt.setString (5, impressao);
*/
System.out.println("Inserindo ...");
preparedStmt.execute(instrucaoSQL);
System.out.println("Inserido com sucesso");
preparedStmt.close();
conexao.close();
}
catch(Exception e){
System.out.println("Erro");
e.printStackTrace();
}
}
public static void main(String[] args){
db banco = new db();
InsereVin(banco,"12345678912345678");
}
}
and the error I'm getting:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?)' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:763)
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648)
at db.InsereVin(db.java:39)
at db.main(db.java:53)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at jdk.compiler/com.sun.tools.javac.launcher.Main.execute(Main.java:419)
at jdk.compiler/com.sun.tools.javac.launcher.Main.run(Main.java:192)
at jdk.compiler/com.sun.tools.javac.launcher.Main.main(Main.java:132)
I really can't understand what is going wrong with my code and I'll be very thankfull if someone could help me.
This line is causing the error:
preparedStmt.execute(instrucaoSQL);
Instead of calling PreparedStatement#execute, you are actually calling a method that PreparedStatement inherits from Statement. See the javadoc for the method you are calling here. See the javadoc for the method you want to call here.
Upon reading the documentation, it should become clear to you that you need to change preparedStmt.execute(instrucaoSQL); to preparedStmt.execute(); in your code.

NoSuchMethodError for different method when invoking java.sql.DriverManager.getConnection()

I'm trying to follow the quick Hello World for connecting a java client to Phoenix. My code is pretty similar to the example, main difference is the kerberos login info in my getConnection() string:
package com.demo.hbase;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class HBaseClient {
public static void main(String[] args) throws SQLException {
Statement stmt = null;
ResultSet rset = null;
Connection con = DriverManager.getConnection("jdbc:phoenix:myHadoopServer1,myHadoopServer2,myHadoopServer3:2181/hbase-secure:myPrinciple:/path/to/my/keytab.keytab");
stmt = con.createStatement();
stmt.executeUpdate("create table test (mykey integer not null primary key, mycolumn varchar)");
stmt.executeUpdate("upsert into test values (1,'Hello')");
stmt.executeUpdate("upsert into test values (2,'World!')");
con.commit();
PreparedStatement statement = con.prepareStatement("select * from test");
rset = statement.executeQuery();
while (rset.next()) {
System.out.println(rset.getString("mycolumn"));
}
statement.close();
con.close();
}
}
When running this I get an exception on the line containing DriverManager.getConnection, but the error is for not being able to find a method in the HBase library, which isn't even being explicitly called in this Hello World. Furthermore, the method that its complaining about not existing definitely does exist!
Full text of the error:
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(Lorg/apache/hadoop/conf/Configuration;ZLjava/util/concurrent/ExecutorService;Lorg/apache/hadoop/hbase/security/User;)Lorg/apache/hadoop/hbase/client/Connection;
at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:439)
at org.apache.hadoop.hbase.client.ConnectionManager.createConnectionInternal(ConnectionManager.java:348)
at org.apache.hadoop.hbase.client.HConnectionManager.createConnection(HConnectionManager.java:144)
at org.apache.phoenix.query.HConnectionFactory$HConnectionFactoryImpl.createConnection(HConnectionFactory.java:47)
at org.apache.phoenix.query.ConnectionQueryServicesImpl.openConnection(ConnectionQueryServicesImpl.java:425)
at org.apache.phoenix.query.ConnectionQueryServicesImpl.access$400(ConnectionQueryServicesImpl.java:267)
at org.apache.phoenix.query.ConnectionQueryServicesImpl$12.call(ConnectionQueryServicesImpl.java:2523)
at org.apache.phoenix.query.ConnectionQueryServicesImpl$12.call(ConnectionQueryServicesImpl.java:2499)
at org.apache.phoenix.util.PhoenixContextExecutor.call(PhoenixContextExecutor.java:76)
at org.apache.phoenix.query.ConnectionQueryServicesImpl.init(ConnectionQueryServicesImpl.java:2499)
at org.apache.phoenix.jdbc.PhoenixDriver.getConnectionQueryServices(PhoenixDriver.java:255)
at org.apache.phoenix.jdbc.PhoenixEmbeddedDriver.createConnection(PhoenixEmbeddedDriver.java:147)
at org.apache.phoenix.jdbc.PhoenixDriver.connect(PhoenixDriver.java:221)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at com.demo.hbase.HBaseClient.main(HBaseClient.java:18)
I tried explicitly importing the ConnectionFactory class, but that didn't change anything. I'm a little at a loss for how to troubleshoot this. The ConnectionFactory class isn't explicitly used anywhere, and ConnectionFactory.createConnection() definitely does exist.

ucanaccess SQL Exception: invalid cursor state: identified cursor is not open

I am a little bit confused,
I am trying to insert multiple rows to MS Access database from a java program using ucanaccess Java library.
I don't understand why the above (check title) SQL Exception is thrown when calling the 2nd insertRow() method?
The Exception is NOT thrown either by calling con.setAutoCommit(false); & con.commit(); methods or by re-executing the SQL query using the command rs = st.executeQuery(sql);. I also do not understand why the problem is solved by doing one of the above. What changes?
Thanks in advance.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class db1 {
private Connection con;
protected Statement st;
protected ResultSet rs;
public db1() {
connect();
}
public void connect() {
try {
String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
Class.forName(driver);
String db = "jdbc:odbc:Database1";
con = DriverManager.getConnection
("jdbc:ucanaccess://C:\\Users\\Κώστας\\Desktop\\Database1.accdb");
st = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE,
ResultSet.HOLD_CURSORS_OVER_COMMIT)
// con.setAutoCommit(false);
String sql = "select * from TableA";
rs = st.executeQuery(sql);
rs.insertRow();
// rs = st.executeQuery(sql);
rs.insertRow(); // HERE the SQL Exception is thrown.
// con.commit();
}
catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
new db1();
}
}
UCanAccess has some known issues with updatable ResultSets because it uses triggers on the HSQLDB backing tables to push the changes to the Access database file. A side effect of those triggers is that they can leave the HSQLDB ResultSet in an invalid state.
The problem you are experiencing may not manifest itself with con.setAutoCommit(false); because the triggers probably don't flush the changes to the Access database until the JDBC transaction is committed.

Error in My java oracle connectivity ... java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I just got some errors in my Java oracle connectivity. Could anyone please help me with this? I have enclosed the code below. I'm getting this error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver..
this is the code
package md5IntegrityCheck;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class MD5IntegrityCheck
{
public static void main(String[] args)
{
String fileName,Md5checksum ,sql;
Connection con;
PreparedStatement pst;
Statement stmt;
ResultSet rs;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 =DriverManager.getConnection("jdbc:odbc:RecordTbl","scott","tiger");
}
catch(Exception ee)
{ee.printStackTrace( );}
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/****insert method******/
private static void setDefaultCloseOperation(String exitOnClose) {
// TODO Auto-generated method stub
}
static void setVisible(boolean b) {
// TODO Auto-generated method stub
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:RecordTbl","scott","tiger");
PreparedStatement pst = con.prepareStatement("insert into RecordTbl values(?,?)");
String fileName = null;
pst.setString(1,fileName);
String Md5checksum = null;
pst.setString(2,Md5checksum);
int i=pst.executeUpdate( );
System.out.println("recorded in database");
con.close( );
}
catch(Exception ee)
{ee.printStackTrace( );}
}
}
if (args.length <= 0)
{
Md5Gui gui = new Md5Gui();
gui.runGui();
}
else
{
DoWork runningProgram = new DoWork();
runningProgram.run(args);
}
}
}
Your question is vague:
In your exception, you're getting a ClassNotFoundException for a driver that pertains to MySQL. On your code, you're using a JDBC-ODBC Driver.
My suggestion is how did you configure your database connectivity. Let's start from there. Also, it would be better to add the exception stack trace to see exactly what's happening.
Edit: Visit this example if you want to know how to configure JDBC connection to Oracle Database. I fully recommend using the Oracle JDBC driver directly instead of connecting it to an ODBC Bridge.
I assume you might be running your program in IDE, so please add drivers jars in the classpath of project
You should look into any 3rd party library you're using whether there a MySQL database driver is needed. Although you write you are using an Oracle driver (though the JdbcOdbcDriver is provided by Java itself and has nothing to do with Oracle DB's) the exception is clearly stating that the MySQL is requested. Since you don't use it in the code you provided, there must be another database connection using MySQL.

Categories

Resources