PrearedStatement executeUpdate() is not working - java

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.

Related

"ORA-01008: not all variables bound"

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);

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";

Getting SQL exception in where clause while inserting data in database through java

I want to store the password for required ID using java. Everything is working fine except that I am getting this Exception
"SQL Exception thrown: 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 '(Pass_word) set Pass_word = 'pass' where ID = 2' at line 1".
I am getting this exception only in update query but not in select query.I am using Eclipse. Can anyone tell me what I am doing is wrong?
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class information {
public static void main(String[] args) {
String password;
ResultSet rs;
String queryString;
int x=1;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost/onlineexam","root", "batch12#nitap");
System.out.print("Database is connected !");
Statement stmt = conn.createStatement();
PreparedStatement pstmt = null;
while(x==1)
{
System.out.println("Press 1 to enter student id");
System.out.println("Press 2 to exit");
Scanner s= new Scanner(System.in);
int choice = s.nextInt();
switch(choice)
{
case 1: System.out.println("Enter the ID of student");
int id = s.nextInt();
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID=" +id;
rs= stmt.executeQuery(queryString);
//System.out.println(rs.getInt("ID"));
while(rs.next())
{
if(rs.getInt("ID")== id)
{
String roll = rs.getString("Roll_no");
String date = rs.getString("Date");
String time = rs.getString("Time");
String c_name = rs.getString("Course_name");
String c_code = rs.getString("Course_code");
password pass1= new password(roll,date,time,c_name,c_code);
pass= pass1.passwd();
System.out.println(pass);
queryString =" Update student_reg(Pass_word) set Pass_word = 'pass' where ID = ?";
//queryString= "INSERT INTO student_reg(Password) VALUES ('password') where ID = ?";
//stmt.executeUpdate(queryString);
//PreparedStatemenet pstmt = conn.preparedStatement("INSERT INTO student_reg(Password) VALUES ('password') where ID = ?");
//pstmt.setLong(1, id);
pstmt = conn.prepareStatement(queryString);
pstmt.setInt(1, id);
int numberOfUpdatedRecords = pstmt.executeUpdate();
s.close();
}
}
break;
case 2: x=0;
}
}
if(conn!= null)
{
stmt.close();
pstmt.close();
conn.close();
conn = null;
}
}
catch(ClassNotFoundException cnf)
{
System.out.println("Driver could not be loaded: " + cnf);
}
catch(SQLException sqle)
{
System.out.println("SQL Exception thrown: " + sqle);
}
catch(Exception e)
{
System.out.print("Do not connect to DB - Error:"+e);
}
}
}
Your code has many problem:
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID= id";
This line you have condition where but you not set the value yet, you should set
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
Better if you take a look at PreparedStatement for prevent SQL Injection as well.
The last one:
queryString= "INSERT INTO student_reg(Password) VALUES ('password') where ID = id";
This line seem you want to update something. Please review it.
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID= id";
should be
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
This would fix the error, but it would be better to use a PreparedStatement, where the query String looks like "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = ?", and you pass the id as a parameter.
It is so obvious because you shouldn't include the 'id' in your query string:
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
Very good hint from #spencer: you can not use WHERE clause in your INSERT INTO statement. Probably you wanted to UPDATE a row with that id. Also it is better to do it using PreparedStatemenet to avoid such mistakes:
conn = DriverManager.getConnection("jdbc:mysql://localhost/onlineexam","root", "batch12#nitap");
PreparedStatemenet pstmt = conn.preparedStatement("UPDATE student_reg SET password = 'password' where ID = ?");
pstmt.setLong(1, id);
int numberOfUpdatedRecords = pstmt.executeUpdate();
I suggest you to rename the column name password, because it is a reserved word in mysql, so you may get strange results working with that column name. Change it to some other thing like: pass_word or passwd , ... . As you may know you can use keywords as column names in your queries using some quotes or other things but it is more safe to rename it to another name, just for hint.
if you use this connection without a connection-pool, you may want to close the Statement and the Connection.
Good Luck.

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