Insert into mysql with preparedstatement not working [duplicate] - java

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.

Related

prepareStatement(String) cannot find symbol

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.

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.

Can I get direct all signature of stored procedure from oracle using jdbc api insted of "select* from "?

I am using JDBC to get matadta of stored procedures from different databases. I am trying to get procedure signatures with parameteres. I have tried to get stored procedure names by using getProcedures() function and parameter name with getProcedureColumns().
The problem is when I am trying to get parameters from procedures/functions in Oracle Database 11g using getProcedureColumns() it will return information for only those procedures which have parameters. How can I get information for all procedures by using JDBC only? I don't want to use sql commands for this. Below is the code I am using for finding parameter information.
package jdbc.core;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.DatabaseMetaData;
import com.mysql.jdbc.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = null;
System.out.println("Got Connection.");
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#192.192.6.144:1521","system","");
java.sql.Statement st = conn.createStatement();
java.sql.DatabaseMetaData dbMetaData = conn.getMetaData();
ResultSet rs = dbMetaData.getProcedureColumns(null, "dbo", "%", "%");
while (rs.next()) {
String procedureName = rs.getString(3);
String columnName = rs.getString(4);
System.out.println("procedureSchema=" + procedureSchema);
System.out.println("procedureName=" + procedureName);
System.out.println("columnName=" + columnName);
}
}

Oracle java connection

I have written a connection code with oracle. But still I am getting errors. I'll type the code of mine here.
import java.sql.*;
public class SimpleOraJava {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// TODO Auto-generated method stub
DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
String serverName="10.20.228.67";
String user="root";
String password="root";
String SID="abc";
String URL="jdbc:oracle:thin:#"+serverName+":"+1520+":"+SID;
Connection conn=DriverManager.getConnection(URL, user, password);
String SQL="Select employeename from employee";
Statement stat=conn.createStatement();
ResultSet rs=stat.executeQuery(SQL);
while (rs.next()){
System.out.println(rs.getInt(1));
}
stat.close();
conn.close();
}
}
It shows error in this line:
DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
The error is on the word Oracle. It is asking me to create class in package oracle.jdbc.driver
Please somebody help!
Okay, assuming that class-paths are set up, and the appropriate .jar files are in the correct directories, the first thing that jumps out is I believe you need to import the package into your class. There should be a import oracle.jdbc.driver.*; line under the import java.sql.*; line also the DriverManager call should be
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
with the lowercase o, it's capitalized in your code.
Another thing might be, the version of the Oracle JDBC, and Oracle client you're using. According to this OTN Discussion post Oracle JDBC 10.2 is the last release to support the package oracle.jdbc.driver.
So basically according to the metalink page if you're using a JDBC 10.2 or older client, something like this will work:
import java.sql.*;
import oracle.jdbc.driver.*;
public class myjdbcapp
{
public static void main(String[] args) throws SQLException
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
String url = "jdbc:oracle:thin:#server:port:orcl";
String userName = "scott";
String password = "tiger";
Connection conn = DriverManager.getConnection (url, userName, password);
OracleCallableStatement myprocst = (OracleCallableStatement)
conn.prepareCall ("begin myproc(?); end;");
// ...
}
}
Clients newer than JDBC 10.2 will need to change import oracle.jdbc.driver.; to import oracle.jdbc.;
DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
The package is oracle.jdbc.driver with a lowercase o.

Categories

Resources