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.
Related
Hi guy's I need to know how can I (insert into) a created table cause I'm getting a lot of errors :
Connection con = DriverManager.getConnection(DB_URL,username,password);
//query for the offer Validity
String query = "SELECT chargingtime,CHARGINGPARTYNUMBER,SUBSCRIBERID,OFFERNAME,OFFERID,prepaidbalance,LIFECYCLE_DAYS,LVL,OPERATIONID FROM ncs_sub_unsub";
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String SUBSCRIBERI = rs.getString("SUBSCRIBERID");
String OFFERNAME = rs.getString("OFFERNAME");
String OFFERID = rs.getString("OFFERID");
String LIFECYCLE_DAYS = rs.getString("LIFECYCLE_DAYS");
int LEVEL1 = rs.getInt("LVL");
String CHARGINGPARTY =rs.getString("CHARGINGPARTYNUMBER");
int OPERATIONID= rs.getInt("OPERATIONID");
float prepaid_balance = rs.getFloat("PREPAIDBALANCE");
LocalDate CHARGINGTIME1 = rs.getObject("CHARGINGTIME", LocalDate.class);
LocalDate CHARGINGTIME7 = CHARGINGTIME1.plusDays(7);
LocalDate CHARGINGTIME14 = CHARGINGTIME1.plusDays(14);
//if the level is one , the time should be 7 days
if(LEVEL1 == 1){
if((OPERATIONID == 4050001 && CHARGINGTIME1.isBefore(CHARGINGTIME7)) || CHARGINGTIME1.isEqual(CHARGINGTIME7)){
String q = String.valueOf(stmt.executeUpdate("INSERT INTO aggregation VALUES (SUBSCRIBERI,CHARGINGPARTY,OPERATIONID,OFFERNAME,prepaid_balance,LIFECYCLE_DAYS,LEVEL1,'S')"));
} else if ((OPERATIONID == 4050018 && CHARGINGTIME7.isAfter(CHARGINGTIME1)) || CHARGINGTIME7.isEqual(CHARGINGTIME1)) {
String q = String.valueOf(stmt.executeUpdate("INSERT INTO aggregation VALUES (SUBSCRIBERI,CHARGINGPARTY,OPERATIONID,OFFERNAME,prepaid_balance,LIFECYCLE_DAYS,LEVEL1,'U')"));
}else {
String q = String.valueOf(stmt.executeUpdate("INSERT INTO aggregation VALUES (SUBSCRIBERI,CHARGINGPARTY,OPERATIONID,OFFERNAME,prepaid_balance,LIFECYCLE_DAYS,LEVEL1,'E')"));
}
}
}
}// end of try
catch (SQLException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
ViewTable();
}
}
The error:
Caused by: Error : 984, Position : 111, Sql = INSERT INTO aggregation VALUES (SUBSCRIBERI,CHARGINGPARTY,OPERATIONID,OFFERNAME,prepaid_balance,LIFECYCLE_DAYS,LEVEL1,'U'), OriginalSql = INSERT INTO aggregation VALUES (SUBSCRIBERI,CHARGINGPARTY,OPERATIONID,OFFERNAME,prepaid_balance,LIFECYCLE_DAYS,LEVEL1,'U'), Error Msg = ORA-00984: column not allowed here
It looks like the Insert sql query is wrong.
I think you are trying to insert String values without '' and String values into float columns.
INSERT INTO aggregation VALUES (SUBSCRIBERI,CHARGINGPARTY,OPERATIONID,OFFERNAME,prepaid_balance,LIFECYCLE_DAYS,LEVEL1,'U')
This is not a valid sql query since prepaid_balance is not a number and SUBSCRIBERI is not a string (try 'SUBSCRIBERI' etc)
stmt.executeUpdate("INSERT INTO aggregation VALUES (SUBSCRIBERI,CHARGINGPARTY,OPERATIONID,OFFERNAME,prepaid_balance,LIFECYCLE_DAYS,LEVEL1,'U')"));
This doesn't work. You can't use java variable names inside a string and expect the system to figure it out. That string is based verbatim to the SQL JDBC driver which is not capable of doing that sort of thing.
What you want is [A] not executeUpdate, it can't do this. You want prepareStatement. The statement would be something like:
"INSERT INTO aggregation VALUES (?,?,?,?,?,?,?,'U')"
and then you use the various .setX methods that PreparedStatement has to set the values: .setString(1, SUBSCRIBERI);, and so on for all the other question marks. Once you've done all that, you can run .executeUpdate() on the prepared statement object.
There are thousands of tutorials out on the web that show you how to use PreparedStatement here.
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
I have a problem updating my table from java.
i need to check colmunID(from my table PRODUCTS) = int id(given by user input) and change thats product price in table to one given by user.
PROBLEM:
static void x(int Userid, int Userprice) {
..........................................
String sql = "UPDATE Product set Price = Userprice where ID=Userid; ";
....}
I get error that i don't have column Userprice or Userid in my database. I don't know how to write this to check int User id which is given as argument in this method and not column in my database table which does not exists.
Assuming that you have both the columns with Integer datatype in DB,
String sql = "UPDATE Product set Price="+Userprice+" where ID="+Userid;
You are not passing the actual values to it and the extra ';' is not required. Also, I suggest you to prefer prepared statements, rather than above approach
While you definitely in production code want to use prepared statements to prevent sql injection, an easy fix would be the below.
String sql = String.format("UPDATE Product set Price = %d where ID=%d ",Userprice,Userid);
String wont evaluate variables in itself.
If the table for Userid does not exist in your database, you will not be able to use this in your SQL query. There are two options for you:
1. Pass the Userid and Userprice as a variables to the SQL query
String sql = "UPDATE Product set Price = " + Userprice + "where ID=" + Userid+ "; "
Or
2. Create the table in the database and join on that
String sql = "Update A Set A.Price = b.Userprice FROM Product as A INNER JOIN User as b on A.Userid = b.ID;"
PreparedStatement ps = null;
Connection con = null;
try {
con = getConnection();
String sql = "UPDATE Product set Price = ? where ID= ? ";
ps = con.prepareStatement(sql);
ps.setString(1, Userprice);
ps.setString(2, Userid);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Product Updated");
} else {
System.out.println("Error Occured");
}
I think this is something you are looking for... The query should not contain ';' in the String for your code
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();
}
}
}
I am writing code in Java and I want to take every time I run this code the next line from a MySQL table.The second time I run this code is this.
String timh1 = "1";
String timh2 = "2";
PreparedStatement st = null;
String sqlGrammes = "SELECT SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE LIMIT ?,? ";
try {
st = connection.prepareStatement(sqlGrammes);
st.setString(1, timh1);
st.setString(2, timh2);
But it shows me this error :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 ''1','2'' at line 1
limit accepts integer parameters, so you should use ints, not Strings:
int timh1 = 1;
int timh2 = 2;
PreparedStatement st = null;
String sqlGrammes = "SELECT SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE LIMIT ?,? ";
try {
st = connection.prepareStatement(sqlGrammes);
st.setInt(1, timh1); // notice the setInt
st.setInt(2, timh2); // here too
I was able to do it without prepared statement
int i = 0;
int j = 1;
sql = "Select SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE limit "+i+ ","+j;
got first row as output.