"ORA-01008: not all variables bound" - java

I used this code for simple displaying data of any randomly selected id but this error is occurring I saw a various post about this error but I didn't any result for my program, please suggest me what is a problem.
I am using following code
public class Demo {
public static void main(String[] args) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:StudentInfo_Oracle","System","Aadi#123");
Scanner s = new Scanner(System.in);
String disq = "Select * from Sample where Id = ?";
System.out.println("Enter id number which data want to display: ");
int id = s.nextInt();
PreparedStatement dis = con.prepareStatement(disq);
dis.execute();
ResultSet rs = dis.getResultSet();
while (rs.next()) {
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
}
}
}

After PreparedStatement set value of ?
PreparedStatement dis = con.prepareStatement(disq);
dis.setInt(1,id);

Related

PrearedStatement executeUpdate() is not working

I'm new to JDBC and using the following code to update the row using MySQL JDBC driver. I have no idea why executeUpdate() is not updating the content in the database.
import java.sql.*;
import java.util.*;
public class UpdateDb {
UpdateDb() throws Exception,SQLException{
Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedb","root","");
String q="update table inserttbl set Name=?, City=? where id=?";
System.out.print("Enter new name to update: ");
String n = sc.nextLine();
System.out.print("Enter new city name to update: ");
String c = sc.nextLine();
System.out.print("Enter previous id: ");
int id = sc.nextInt();
PreparedStatement ps = conn.prepareStatement(q);
ps.setString(1, n);
ps.setString(2, c);
ps.setInt(3, id);
ps.executeUpdate();
System.out.print("updated");
conn.close();
}
public static void main(String[] arg) {
try {
UpdateDb up = new UpdateDb();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
Can anyone help me?
Your query string is wrong. It should be something like this:
String updateQuery = "UPDATE inserttbl SET Name=?, City=? WHERE id=?";
Look here for the proper syntax of update: https://www.mysqltutorial.org/mysql-jdbc-update
Also if you want to update then use an update table command. The command that you used for insert is wrong.
Also for error print out the exception that you logged.

Displaying data from two tables in java mysql

i want to display messages with the sender name. The outer while loop is working fine but there is some problem in the inner while loop. I have tried a lot to figure out but got no result. Can anyone help me? I'll very thankful.
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class Messages extends Login {
static Scanner in = new Scanner(System.in);
public static void main(String args[]) throws Exception{
boolean isLoggedin = login();
String msg = "";
String senName = "";
if(isLoggedin) {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?verifyServerCertificate=false&useSSL=false", "root", "");
Statement st = con.createStatement();
Statement st1 = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM chat");
ResultSet rs1 = st1.executeQuery("SELECT * FROM data");
while(rs.next()) {
int dbRecID = rs.getInt("reciever_id");
if(dbRecID == user_id) {
msg = rs.getString("message");
int dbSenID = rs.getInt("sender_id");
while(rs1.next()) {
int senID = rs1.getInt("id");
if(senID == dbSenID) {
senName = rs1.getString("name");
}
}
System.out.println(senName+" sent you a message: "+msg);
}
}
}
else {
System.out.print("Login Unsuccessful");
}
}
}
Output
Ali Ahmed sent you a message: How are you?
Ali Ahmed sent you a message: Hi!
Required Output
Ali Ahmed sent you a message: How are you?
Hamza sent you a message: Hi!
The issue comes from the two nested while loops.
The query ResultSet rs1 = st1.executeQuery("SELECT * FROM data"); is executed just once.
The first time you loop on while(rs.next()) you will fetch the whole content of rs1 to check if the sender id is the right one.
Then on the second iteration on while(rs.next()) because rs1 has been already fetched while(rs1.next()) wil return false.
In order to have your code working you should move the execution of the second query to get something like this:
while(rs.next()) {
...
ResultSet rs1 = st1.executeQuery("SELECT * FROM data");
while(rs1.next()) {
...
}
...
}
But I think that it would be a better solution to make just one SQL
request joining the datas of the two tables and including the where
condition.

How to use IO with JDBC connection

this is my method for writing db query.
public static void post() throws Exception{
int clientMPNumber = Parcel.typeClientNumber();
int orderPassword = Parcel.generatePass();
try{
Connection con = ConnectionDB.getConnection();
PreparedStatement posted = con.prepareStatement("UPDATE `BankDB`.`Info` SET `Money`='77777' WHERE `ClientID`='77' AND `ClientPass`='1111';");
posted.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally{
System.out.println("Insert completed");
}
}
I'm trying to do something like ATM machine. So I expect that user types his ID and password, and then the user can withdraw money or deposit money.
So I want to check login data correctness. User needs to type correct ID/password [logins/passwords are placed in MySQL DB].
PreparedStatement posted = con.prepareStatement("UPDATE `BankDB`.`Info` SET `Money`='77777' WHERE `ClientID`='USER TYPES IT' AND `ClientPass`='USER TYPES IT';");
There is a sentence: "USER TYPES IT", this is my problem. I want to use here a Scanner or something like this. How can I do it?
A prototype for you (just an example, you should split up the part get userid, password, outside of this function for better practice):
public void post (){
Scanner sc = new Scanner(System.in);
System.out.println ("please enter user id:");
String userId = sc.nextLine();
System.out.println("please enter password:");
String pass = sc.nextLine();
Connection con;
PreparedStatement posted;
try {
con = ConnectionDB.getConnection();
String sql = "UPDATE `BankDB`.`Info` SET `Money`='77777' WHERE `ClientID`=? AND `ClientPass`=?";
posted = con.prepareStatement(sql);
posted.setString(1, userId);
posted.setString(2, pass);
posted.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
posted.close();
con.close();
}
}

Why doesnt my main class run the method i called?

i have a question: i am trying to make an insert-query with in java using the jdbc for mysql. I think my code is correct, but somehow i can't run the method i call in my main class. Here's my method i wanna call code:
public void wijzigAfspraak() {
try {
Statement stmt2 = conn.createStatement();
String query2 = "";
rs = stmt2.executeQuery(query2);
System.out.println("query uitgevoerd");
while (rs.next()){
String titel = rs.getString(1);
String datum = rs.getString(2);
int urgentie = rs.getInt(3);
String beschrijving = rs.getString(4);
System.out.println(titel+datum+urgentie+beschrijving);
}
}
catch (SQLException e){
e.printStackTrace();
}
}
here is my main class:
public class Main {
public static void main(String[] args){
AfspraakDaoImpl adi = new AfspraakDaoImpl();
Afspraak afs = new Afspraak("","",1,"");
afs.setTitel("hond");
afs.setAfspraakDatum("12juni");
afs.setUrgentie(123);
afs.setBeschrijving("test");
adi.voegAfspraakToe();
adi.wijzigAfspraak();
}
my console doesn't print anything and my database shows no difference in data, which means it didn't work right?
Thanks in advance!
Looks like you're executing empty SQL query here:
String query2 = "";
rs = stmt2.executeQuery(query2);
If you want to execute INSERT statement, You should invoke executeUpdate() method on you statement object stmt2 and pass SQL string as a parameter.
Moreover, consider using PreparedStatement instead of Statement as follows:
String sql = "INSERT INTO foo(value) VALUES(?)";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, "bar");
ps.executeUpdate();
} catch (SQLException e) {
// handle error
}
One more thing. Looks like you keep ResultSet rs as a class field. Don't do so, try to minimize number of mutable state variables of your class, try to keep your components light and stateless. It's better to keep Statement and ResultSetin try-with-resources block.
Since you're using a DAO and using MYSQL Database ( witch is not specified here ;) ):
public void wijzigAfspraak(String 1, String 2, String 3, etc..) {
try {
Statement stmt2 = conn.createStatement();
String query2 = "insert into afspraken (column_1, column_2, etc...) values ( String 1, String 2, etc..)"; --> these values come from the wijzigafspraak(String 1, String 2, etc..)
stm2.executeUpdate(query2);
System.out.println("query is inserted correctly");
You do not want to use the rs.next(), witch is used for a "SELECT-STATEMENT", you do not receive data, vut you insert it.
then, your main class:
public class Main {
public static void main(String[] args){
AfspraakDaoImpl adi = new AfspraakDaoImpl();
Afspraak afs = new Afspraak("","",1,"");
afs.setTitel("hond");
afs.setAfspraakDatum("12juni");
afs.setUrgentie(123);
afs.setBeschrijving("test");
//adi.voegAfspraakToe();//this is not specified?? and probably does not work either
adi.wijzigAfspraak(afs.getTitel(), afs.getAfspraakDatum(), etc..);
where is your sql statement ? It should be :
String query2 = "select titel,datum,urgentie,beschrijving from Afspraak";

Looking up data in database from user

I am trying to let a user lookup a football result, and the database displays that result from the database, but i keep getting this error:
Exception in thread "main" java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
This is my "useFootballBean.java" bean:
package results;
import results.*;
import java.util.*;
import java.sql.*;
public class UseFootballBean
{
public static void main(String[] args)
throws SQLException, ClassNotFoundException
{
Scanner keyboard = new Scanner(System.in);
String home;
ResultsBean resultsBean = new ResultsBean();
System.out.print("\nEnter Team: ");
home = keyboard.next();
home = resultsBean.getHome(home);
if (home.equals(null))
System.out.println(
"\n*** No such Team ***");
else
System.out.println("\nTeam " + home);
}
}
This is my "resultsBean.java" bean
package results;
import java.sql.*;
public class ResultsBean
{
private Connection connection;
private Statement statement;
private ResultSet results;
public String getHome(String enter)
throws SQLException, ClassNotFoundException
{
String query;
String team = null;
connectAndCreateStatement();
query = "SELECT * FROM Results WHERE homeTeam = "
+ enter;
results = statement.executeQuery(query);
if (results.next())
team = results.getString("homeTeam");
connection.close();
return team;
}
private void connectAndCreateStatement()
throws SQLException, ClassNotFoundException
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection(
"jdbc:odbc:FootballData","","");
statement = connection.createStatement();
}
}
I think you are missing the single quotes required in where clause of query while comparing against a string value. Here you go:
where keyword_name='"+keyword_name+"'"
query = "SELECT * FROM Results WHERE homeTeam = " + '"+ enter + "'";
Since your query parameter is a string, you need to enclose it in quotes:
"SELECT * FROM Results WHERE homeTeam = '" + enter + "'";
However, this is still a bad approach, because it leaves you vulnerable to SQL injection (Remember Bobby Tables?), and will break if the user enters a team name containing quote characters (like England's Greatest Team). Therefore, you should use a PreparedStatement (see Java tutorial).
You are missing single quotation in your Sql Query
query = "SELECT * FROM Results WHERE homeTeam = '"
+ enter+"'";
OR with PreparedStatement to accept quotation
PreparedStatement stmt = null;
String sql;
ResultSet rows=null
try {
sql = "select * from Results where homeTeam=?"
stmt = theConn.prepareStatement(sql);
stmt.setString(1, "Team with ' are permitted!");
rows = stmt.executeQuery();
stmt.close();
}
catch (Exception e){
e.printStackTrace();
}
finally { if (stmt != null) {
stmt.close();
}
Thanks

Categories

Resources