I am having really strange problem. I have just written a code that should create procedure and then execute it. But it is giving me this error:
Exception in thread "main" java.sql.SQLException: [Microsoft][Driver ODBC Microsoft Access] Syntax error in statement CREATE TABLE
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
at mDat.procedures.createProcedure(procedures.java:25)
at mDat.procedures.main(procedures.java:14)
Here is my code:
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class procedures {
static Connection con;
static String procedure;
public static void main(String[]args) throws ClassNotFoundException, SQLException{
getConnection("jdbc:odbc:TestDatabaze");
createProcedure();
executeProcedure();
con.close();
}
static void getConnection(String connection) throws ClassNotFoundException, SQLException{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(connection);
}
public static void createProcedure() throws SQLException{
procedure="CREATE PROCEDURE newest_user AS SELECT Firstname, Lastname FROM members WHERE ID= max(ID)";
Statement s = con.createStatement();
s.execute(procedure);
s.close();
}
public static void executeProcedure() throws SQLException{
CallableStatement cs=con.prepareCall("{CALL newest_user}");
String fn=cs.getString(1);
String ln=cs.getString(2);
System.out.println("Name of the newest user in database is "+fn+" "+ln);
}
}
I really have no idea why it is giving me that error, becouse there is no code for creating table. Thank you for your help.
Related
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.
In JDBC, I want to insert data using input from the keyboard.
As a result of finding the method, I came to know the scanner and wrote the code as follows.
package DB;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;
class insert{
Connection con;
Statement stmt;
Scanner scan = new Scanner(Syetem.in);
public insert() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#localhost:1521:orcl";
con = DriverManager.getConnection(url,"scott","1234");
stmt = con.createStatement();
} catch(ClassNotFoundException ce) {
System.out.println(ce.getMessage());
} catch(SQLException se){
System.out.println(se.getMessage());
}
}
public void disconnect() throws SQLException{
if (stmt!=null) stmt.close();
if (con!=null) con.close();
}
public void insert() throws SQLException{
System.out.println("name:")
String employee_name=scan.next();
System.out.println("domain:")
String street=scan.next();
System.out.println("country:")
String city=scan.next();
String sql="insert into information values('"+name+"', '"+domain+"', '"+country+"')";
int n=stmt.executeUpdate(sql);
}
}
But it didn't run and got an error ...
The default method cannot be found in the class. Define a default method in the following format. public static void main (String [] args)
Where should I put the main function to fix the error?
What is the problem? The name of the table to be inserted is 'information'.
Any help would be greatly appreciated
Because JDBC is not yet familiar, if possible, if you write a full query including a connection as in the above query, I would be very grateful.
*my oracle version is 11g
For your code to run you need to provide a method that works as an entry point for your program, that method has the signature public static void main(String[] args) besides that, your class should be named Insert with capital I first because thats de standard y second because you have a method called insert, you will need to have something like this:
public class Insert {
public Insert() {
...
}
public void disconnect() throws SQLException {
...
}
public void insert() throws SQLException {
...
}
public static void main(String[] args) {
new Insert().insert();
}
}
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.
it seems my code is not working. I am trying to extract data from microsoft NAV Cronus DB, but it appears JAVA can't find the table to print.
So I have 2 classes - DAL & Controller
DAL:
import java.sql.*;
public class DAL {
private static String connStr = "jdbc:sqlserver://Localhost;Databases=CronusDB;user=root;password=root;";
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(connStr);
}
public static ResultSet findEmployeeData() throws SQLException {
Statement stmt;
stmt = getConn().createStatement();
String sqlStr = "select [No_], [First Name], [Last Name], [Initials], [Job Title] from [CRONUS Sverige AB$Employee];";
ResultSet rset = stmt.executeQuery(sqlStr);
return rset;
}
}
Connector:
import java.sql.*;
import t3.isprojekt.uppg2.dal.DAL;
public class Controller {
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
DAL.getConn();
System.out.println("Connection Success!");
System.out.println(DAL.findEmployeeData());
}
}
When trying to execute the code I recieve the following error:
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'CRONUS Sverige AB$Employee'.
The problem is that the table does exist, and I have tried putting .dbo in front without success. Any ideas?
It seems like the database is very sensitive to upper- & lowercase letters. The tables are listed as "CRONUS Sverige..." in MSSQLServer, but when copying the name directly into JAVA it is pasted as "CRONUS SVERIGE" (uppercase). So finally got this working!
I'm trying to connect to a MySQL database, I created the SQL database with phpmyadmin on localhost. My code seems correct and I have the JAR file added to eclipse. I have googled the error and found on here many topics that are the same but haven't been able to resolve the problem. Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class dbconnection {
public static void main (String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:msql://localhost:3306/g52apr","root", "");
java.sql.PreparedStatement statement = con.prepareStatement("select * from std_details");
ResultSet result = statement.executeQuery();
while (result.next()){
System.out.println(result.getString(1) + " " + result.getString(2));
}
}
}
This is the exact error:
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver://localhost:3306/g52apr
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at dbconnection.main(dbconnection.java:10)
"jdbc:msql://localhost:3306/g52apr"
should be:
"jdbc:mysql://localhost:3306/g52apr"
Edited Changed SQL Server reference to MySql