java.sql.SQLSyntaxErrorException: ORA-01722: invalid number_where IN - java

I'm trying to execute the code below. First sql query gave me some needed 'IMSI' number which I store in 's' variable and than I used it to select second and third select query.
When I exclude second query everything went OK. Also when I replace "+s+" with '21901123456456' which is value of s variable, code finish successfully.
But when I execute code as below I got error from subject.
import java.sql.*;
import java.util.Scanner;
class stanjeBroja{
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
System.out.println("Unesi MSISDN");
// get user input for min range
String min=reader.nextLine();
String s = "";
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:#ip:port:sid","user","pass");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("SELECT
SUBSCRIBERKEY,ALTERNATESUBSCRIBERKEY FROM
TERTIOTEST.ALTERNATESUBSCRIBERKEY
WHERE ALTERNATESUBSCRIBERKEY ="+min+"");
while(rs.next()){
System.out.println("IMSI: "+rs.getString(1)+" MSISDN:
"+rs.getString(2)+" ");
s = rs.getString(1);
}
ResultSet rs1=stmt.executeQuery("SELECT servicename FROM
TERTIOTEST.SUBSCRIBERSERVICE WHERE SUBSCRIBERKEY = "+s+"AND servicename
IN
('STD','VPNNUM','HLR','VPNUNR','STDHYB','VOXX','VPNFA')");
while(rs1.next()){
System.out.println("SERVISI: "+rs1.getString(1)+" ");
}
ResultSet rs2=stmt.executeQuery("SELECT PARAMETERVALUE FROM
TERTIOTEST.SERVICEPARAMETER WHERE SUBSCRIBERKEY = "+s+"AND servicename =
'TARIFF' AND PARAMETERNAME = 'tariff'");
while(rs2.next()){
System.out.println("TARIFA: "+rs2.getString(1)+" ");
}
//step5 close the connection object
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}

you select string needs some improvements
space before AND
s is a string so you have to pass it a string in your select so add ' around.
to avoid that, you should use prepared Statement!
"SELECT PARAMETERVALUE FROM
TERTIOTEST.SERVICEPARAMETER WHERE SUBSCRIBERKEY = '"+s+"' AND servicename =
'TARIFF' AND PARAMETERNAME = 'tariff'"
you should check both of your select statements

Related

JDBC - ORA-00984: column not allowed here

import java.util.*;
import java.sql.*;
public class Jdbc {
public static void main(String j[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Id:-");
int id = sc.nextInt();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "System", "Mohit");
String sql = "insert into st values(id)";
Statement stmt = conn.createStatement();
boolean res = stmt.execute(sql);
if (!res) {
System.out.println("Value Inserted");
} else {
System.out.println("Value Not Inserted");
}
} catch (Exception k) {
System.out.println("Exception is:-" + k);
}
}
}
Here In My Code I want insert value in database but it throws me exception, while in Statement Interface we cannot Pass value Dynamically But we can Pass Value Manually
C:\Users\MOHIT\Desktop\PACK>java Jdbc
Enter Id:-0 0
Exception is:-java.sql.SQLException: ORA-00984: column not allowed here
About the error
From the link here
An ORA-00984 will be thrown if a column name (like in the VALUES
clause of an INSERT statement), is used in an expression where it is
not permitted. You may have used a column name in an expression where
it is not permitted. Typically, ORA-00984 occurs while including a
column name in the VALUES clause of an INSERT statement.
To correct ORA-00984, you simply need to view the syntax of the SQL
statement and only use column names where they are appropriate.
You may also find it appropriate to include a character value, in the
INSERT statement, instead of the column name.
Solutions
If you look closer of your query then you find that the syntax is not correct here is the correct syntax of insertion :
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
If you want to pass all the column then you dont need to specify the columns names.
INSERT INTO table_name VALUES (value1, value2);
If your table contain only id then you can use :
String sql = "insert into st values(" + id + ")";
//---concat your id with your query-^--^-^----
If your table contain multiple columns then you can use :
String sql = "insert into st(id) values(" + id + ")";
//---------------------------^^-------------^^-------
Note
Statement can cause a syntax error or an SQL Injection you have to use PreparedStetement
So instead you can use :
String sql="insert into st values(?)";
PreparedStatement insert = connection.prepareStatement(sql);
insert.setInt(1, id);
boolean res = insert.execute(sql);
...
The problem is with your Query
when you say to the DB: "insert into st values(id)";
the db does not know what "id" is . It tries to guess that it is a column, since it is an element not enclosed in quotes, which means it is not a string value.
But there is not such column available at that time which is indicated by the raised Exception.
A way to do it is instead with prepared statement as stated by YCF_L. Also it is a good idea to always close the ResultSet (you don't have one here), statement, and connection.
import java.util.*;
import java.sql.*;
public class Jdbc {
public static void main(String j[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Id:-");
int id = sc.nextInt();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "System", "Mohit");
String sql="insert into st values(?)";
PreparedStatement psmt = connection.prepareStatement(sql);
psmt.setInt(1, id);
boolean res = psmt.executeUpdate();
if (!res) {
System.out.println("Value Inserted");
} else {
System.out.println("Value Not Inserted");
}
} catch (Exception k) {
System.out.println("Exception is:-" + k);
}
finally {
psmt.close();
conn.close();
}
}
}

how to insert bulk data from one database to another data base same structure using java

I have two SQL server running on two different location having same structure but different IP a = 100.0.0.1 and IP b = 192.0.0.1. I have a table a.table and b.table of same structure. Now i want to move all data that is in a. Table from 100.0.0.1 machine to b.table machine 192.0.0.1 .I want to transfer this data using java either connection or by hibernate. Currently i am doing this manually by running SQL query.
Here is the code you can use
import java.sql.*;
import java.io.*;
import java.util.*;
public class test1
{
public static void main(String[] argv) throws Exception
{
try
{
Connection con = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/old","user","pass");
Connection con1 = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/new","user","pass");
String sql = "INSERT INTO users("+ "name,"+ "active,"+ "login,"+ "password)"+ "VALUES(?,?,?,?)";
Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
PreparedStatement pstmt = con1.prepareStatement(sql);
ResultSet rs = statement.executeQuery("SELECT * FROM users");
while ( rs.next() )
{
String nm = rs.getString(2);
Boolean ac = rs.getBoolean(3);
String log = rs.getString(4);
String pass = rs.getString(5);
pstmt.setString(1, nm);
pstmt.setBoolean(2, ac);
pstmt.setString(3, log);
pstmt.setString(4, pass);
pstmt.executeUpdate();
}
con.close();
con1.close();
}
catch (SQLException e)
{
System.out.println("could not get JDBC connection: " +e);
}
}
}
Create a connection with something like this
Connection con=DriverManager.getConnection(url, dbProperties);
//then create a query
String query = "select * from a.table";
Statement statement = connect.createStatement(query);
save result in resultset or somewhere else : ResultSet rs = statement.executeQuery(); then create a second connection to your other database like above and call an insert for each result in your resultset. there might be much better methods to insert so much data. i hear about bulk operations but i don't know how they work

Parameter not set error in Prepared statement

I'm trying to execute a prepared statement in JDBC, and everytime I execute it I get the error message "Paramater not set".
I have tried repeatedly to check for unset parameters - but I only have the one. This leads me to believe it is another foolish error on my part.
If you could point this out to me, I would be very grateful
public book search(String key){
book temp = null;
try {
String stmt = "SELECT BookID, Title, Author, Media, Available FROM BOOK WHERE Title LIKE ?;";
connection = DatabaseConnection();
PreparedStatement preparedStmt = connection.prepareStatement(stmt);
System.out.println(key);
preparedStmt.setObject(1, key);//the name
statement = connection.prepareStatement(stmt); //Using Prepared Statements prepare the query
resultSet = statement.executeQuery(); //Execute the query
while (resultSet.next()) {
int bookID = resultSet.getInt("BookID");//Get the userName
String title = resultSet.getString("Title"); //Get the score
String author = resultSet.getString("Author"); //Get the score
String media = resultSet.getString("Media"); //Get the score
boolean available = resultSet.getBoolean("Available"); //Get the score
temp = new book(title,author,media,available,bookID);
}
connection.close(); //close connection
} catch (SQLException e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return temp;
}
You're calling prepareStatement twice, setting the parameter on the first one but then calling executeQuery on the second.
It's not clear where you're event declaring statement or resultSet, but you want:
PreparedStatement preparedStmt = connection.prepareStatement(stmt);
preparedStmt.setString(1, key);
ResultSet resultSet = preparedStmt.executeQuery();
Note that I've made resultSet a local variable - you really don't want it to be a field... there's also no reason for your temp variable as you can just return directly from the while loop. (I've changed the code to use setString instead of setObject, too...)
You should use try-with-resources statements to close both the statement and the result set automatically...)

SQL query not working for MySQL

I want to update the esal of emp table in my database dynamically but the query is generating error
import java.sql.*;
import java.util.*;
class JdbcEx6
{
public static void main(String args[])throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection ob = DriverManager.getConnection("jdbc:odbc:mysql1","root","root123");
Statement st = ob.createStatement();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the empid");
int eno = sc.nextInt();
System.out.println("Enter the increment");
int inc = sc.nextInt();
String myquery = "update emp set esal=esal+"+inc+"where eno="+eno;/*error here*/
int count = st.executeUpdate(myquery);
ob.close();
if(count==0)
System.out.println("Invalid employee Id provided");
else
System.out.println("Updated successfully");
}
}
/*manual that corresponds to your MySQL server version for the right syntax to use near 'eno=100' at line 1
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:3110)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:338)
at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(JdbcOdbcStatement.java:288)
at JdbcEx6.main(a7.java:18)*/
As others explain, the problem can be solved by adding a whitespace to the where:
String myquery = "update emp set esal=esal+" + inc + " where eno="+eno;
//....................................................^ here
int count = st.executeUpdate(myquery);
A better solution would be to use PreparedStatement rather than plain string concatenation. Here's an example:
//query is more readable and easier to understand
//this way is easier to spot problems in the query
//? means a parameter to use in the query
String myquery = "update emp set esal=(esal+?) where eno=?";
//the connection prepares the query
PreparedStatement pstmt = ob.prepareStatement(myquery);
//set the parameters in the PreparedStatement
pstmt.setInt(1, inc);
pstmt.setInt(2, eno);
//execute the statement, which will replace the ? by the parameters
int count = pstmt.executeUpdate();
String myquery = "update emp set esal=(esal+'"+inc+"') where eno='"+eno"';
This works
You are not including spaces correctly in your query. SQL queries in java need spaces correctly just like they do in standard SQL usage.

A lock could not obtained within the time requested issue

The title is the error I'm getting, when I click load my program freezes. I assume it's because I'm doing a statement inside a statement, but from what I see it's the only solution to my issue. By loading, I want to just repopulate the list of patients, but to do so I need to do their conditions also. The code works, the bottom method is what I'm trying to fix. I think the issue is that I have 2 statements open but I am not sure.
load:
public void DatabaseLoad()
{
try
{
String Name = "Wayne";
String Pass= "Wayne";
String Host = "jdbc:derby://localhost:1527/Patients";
Connection con = DriverManager.getConnection( Host,Name, Pass);
PatientList.clear();
Statement stmt8 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL8 = "SELECT * FROM PATIENTS";
ResultSet rs8 = stmt8.executeQuery( SQL8 );
ArrayList<PatientCondition> PatientConditions1 = new ArrayList();
while(rs8.next())
{
PatientConditions1 = LoadPatientConditions();
}
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM PATIENTS";
ResultSet rs = stmt.executeQuery( SQL );
while(rs.next())
{
int id = (rs.getInt("ID"));
String name = (rs.getString("NAME"));
int age = (rs.getInt("AGE"));
String address = (rs.getString("ADDRESS"));
String sex = (rs.getString("SEX"));
String phone = (rs.getString("PHONE"));
Patient p = new Patient(id, name, age, address, sex, phone,
PatientConditions1);
PatientList.add(p);
}
UpdateTable();
UpdateAllViews();
DefaultListModel PatientListModel = new DefaultListModel();
for (Patient s : PatientList) {
PatientListModel.addElement(s.getAccountNumber() + "-" + s.getName());
}
PatientJList.setModel(PatientListModel);
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
}
This is the method that returns the ArrayList of patient conditions
public ArrayList LoadPatientConditions()
{
ArrayList<PatientCondition> PatientConditionsTemp = new ArrayList();
try
{
String Name = "Wayne";
String Pass= "Wayne";
String Host = "jdbc:derby://localhost:1527/Patients";
Connection con = DriverManager.getConnection( Host,Name, Pass);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM PATIENTCONDITIONS";
ResultSet rs5 = stmt.executeQuery( SQL );
int e = 0;
while(rs5.next())
{
e++;
String ConName = (rs5.getString("CONDITION"));
PatientCondition k = new PatientCondition(e,ConName);
PatientConditionsTemp.add(k);
}
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
return PatientConditionsTemp;
}
I had a similar problem.
I was connecting to derby db hosted on local server.
I created 2 simultaneous connections:
With squirrel
With ij tool
When a connection makes a modification on a table, it first gets a lock for the particular table.
This lock is released by the connection only after committing the transaction.
Thus if the second connection tries to read/write the same table, a msg prompts saying:
ERROR 40XL1: A lock could not be obtained within the time requested
To fix this, the connection which modified the table has to commit its transaction.
Hope this helps !
Here is a good place to start: http://wiki.apache.org/db-derby/LockDebugging
You need to close your statement and result set as well so that when you restart your program they won't be open. Add stmt.close(); and rs.close(); at the end of your lines of code within the try and catch statement.
Why could you not use the same connection object to do both the queries?
Like pass that connection object to the LoadPatientConditions() as a parameter and use it there.

Categories