Parameter index out of range (3 > number of parameters, which is 2) - java

public static int updateApproved(admin u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("update admission set status=? where admiss_id=?");
ps.setString(1,u.getStatus());
ps.setInt(2,u.getAdmiss_id());
status=ps.executeUpdate();
PreparedStatement ps2=con.prepareStatement("insert into patient(username,password,email,sex,level,fullname,age,bday,blood,address,vaccines,fam_his,surgery,medicine_taken) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,u.getUsername());
ps.setString(2,u.getPassword());
ps.setString(3,u.getEmail());
ps.setString(4,u.getSex());
ps.setInt(5,u.getLevel());
ps.setString(6,u.getFullname());
ps.setInt(7,u.getAge());
ps.setString(8,u.getBday());
ps.setString(9,u.getAddress());
ps.setString(10,u.getBlood());
ps.setString(11,u.getVaccines());
ps.setString(12,u.getFam_his());
ps.setString(13,u.getSurgery());
ps.setString(14,u.getMedicine_taken());
status=ps2.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2). Why is this always the error? i have counter the ranges of the parameter, but i still get that error.

PreparedStatement ps2=con.prepareStatement("insert into patient(username,password,email,sex,level,fullname,age,bday,blood,address,vaccines,fam_his,surgery,medicine_taken) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,u.getUsername()); // ps has this
ps.setString(2,u.getPassword()); // ps has this
ps.setString(3,u.getEmail()); // ps does not have this, it only has 2 ?'s in it, so it explodes
You're making PreparedStatement ps2 but your setStrings are all on ps... You need to update those to use ps2

The problem is you have misused the variables ps and ps2.
As you have created a PreparedStatement variable above, you can use it again without creating a new one.
ps = con.prepareStatement("insert into patient
(username, password, email, sex,
level, fullname, age, bday, blood, address, vaccines, fam_his, surgery, medicine_taken)
values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

Related

SQL Syntax error near ' 'x')' at line 1 (Insert statement)

I'm getting problems trying to run this simple sql statement.
try{
stm.executeUpdate("INSERT INTO exam_somatique_6_12(id_p, id_m, id_u, Date, age, poids, taille, TA, exam_clinique, acuite_visuelle, acuite_auditive, age_puberte, conclusion) VALUES ("+idpat+","+idmed+","+idum+",'"+currentdate+"',"+txtage.getText()+","+txtpoids.getText()+","+txttaille.getText()+","+txtta.getText()+",'"+Clinique+"','"+Visuelle+"', '"+Auditive+"', "+Signe+", '"+txtobservation.getText()+"')");
}
catch(SQLException e1)
{
System.err.println(e1.getMessage());
}
dispose();
I have no problem when executing it on mysql, but as soon as I try to do it in Java, I get this message error :
syntax error near ' 'x')' at line 1
And x is the result of the txtobservation.getText().
Also, I'm pretty sure it's not a quote problem, I'm using ' ' when it's a text, and not doing it when it's an integer.
Thanks for your help.
You have to use PreparedStatement instead it is more secure and more helpful
String query = "INSERT INTO table(id_p, id_m, id_u, Date, age, poids, taille,
TA, clinique, visuelle, auditive, puberte, observation)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement ps = connection.prepareStatement(query) {
ps.setInt(1, idpat);//set values to your query
ps.setInt(2, idmed);
....
ps.executeUpdate();//execute your query
}
Note
getText it return String and not int and not float if txtage.getText() is int you have to convert it to int you can use :
Integer.parseInt(txtage.getText());//get int value form a String
Float.parseFloat(txtpoids.getText());//get float value from a String
and so on

PreparedStatement - syntax error

I have a problem with PreparedStatement.
This is my function that adds new user to MySQL database:
public static void createUser(String fn, String sn, String log, String pass, int accNum, String qst, String answ) {
try {
Connection conn = (Connection) mySQLConnector.getConnection();
PreparedStatement ps = (PreparedStatement) conn.prepareStatement(
"INSERT INTO users"
+ "(FirstName, LastName, Login, Password, AccountNumber, Ballance, Question, Answer)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?");
ps.setString(1, fn);
ps.setString(2, sn);
ps.setString(3, log);
ps.setString(4, pass);
ps.setInt(5, accNum);
ps.setDouble(6, 0);
ps.setString(7, qst);
ps.setString(8, answ);
ps.executeUpdate();
ps.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
And this is an error that I get:
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
I have no idea what is wrong with my query. ColumnNames are ok, function arguments are also ok.
I've tried adding '' to columns names (like that: 'FirstName') but i t still doesn't work...
EDIT:
Adding spaces did not helped.I even made it in one line:
"INSERT INTO users (FirstName, LastName, Login, Password,
AccountNumber, Ballance, Question, Answer) VALUES (?, ?, ?, ?, ?, ?,
?, ?)"
and still gives the same error
You are missing spaces. Change your SQL to :
"INSERT INTO users " // space added
+ "(FirstName, LastName, Login, Password, AccountNumber, Ballance, Question, Answer) " // space added
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
EDIT : I missed the missing closing bracket at the end of the VALUES clause.
I think you just need to add spaces and bracket
PreparedStatement ps = (PreparedStatement) conn.prepareStatement(
"INSERT INTO users "
+ "(FirstName, LastName, Login, Password, AccountNumber, Ballance, Question, Answer) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
Fix this:
"VALUES (?, ?, ?, ?, ?, ?, ?, ?");
to this:
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

Prepared statement insert into MySQL from Java

Ok, I know this has been beaten to death in other posts but I have tried to no avail to get this INSERT command to work. I am using MySQL 5.6 with a JDBC connector. I am reading in String variables from a GUI and trying to use them in the INSERT. I have tried using ", `, ' and every combination out there to do this and nothing. This is a pretty straight forward application so what am I missing. Yes the variables do have values in them, I checked.
try
{
String sql = "INSERT INTO customer(firstname, lastname, address, city, state, zip, phone, email)VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, custFirst);
preparedStatement.setString(2, custLast);
preparedStatement.setString(3, custAddress);
preparedStatement.setString(4, custCity);
preparedStatement.setString(5, custState);
preparedStatement.setString(6, custZip);
preparedStatement.setString(7, custPhone);
preparedStatement.setString(8, custEmail);
preparedStatement.executeUpdate();
}
catch(Exception err)
{
System.err.println("Error: " + err.getMessage());
}
You are missing a space in your query statement:
"INSERT INTO customer(firstname, lastname, address, city, state, zip, phone, email)VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
^
should be
"INSERT INTO customer(firstname, lastname, address, city, state, zip, phone, email) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
I found that it really really helps if you are connected to the database BEFORE you try to insert something into it. I had forgot to include a connect statement in my code. Once I added that it worked like a charm. Imagine that...

prepared statement

how can i write prepared statement instead of this: please help me
String qry= "INSERT INTO
Registration1(RegistrationNo,Date,SeniorPerson,NativePlace,Kul,Gotra,KulSwami,ResidensialAddress,PinCode,STDcode,TelephoneNo,MobileNo,Email,Website,Education,Branch,BirthDate,BloodGroup) VALUES('"+regno+"','"+dt+"','"+nm+"','"+place+"','"+kul+"','"+gotra+"','"+kswami+"','"+raddr+"','"+pincode+"','"+stdcd+"','"+tele+"','"+mno+"','"+email+"','"+website+"','"+education+"','"+branch+"','"+bdt+"','"+bloodgrp+"')";
stmt.executeUpdate(qry);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO Registration1(RegistrationNo,Date,SeniorPerson,NativePlace,Kul,Gotra,KulSwami,ResidensialAddress,PinCode,STDcode,TelephoneNo,MobileNo,Email,Website,Education,Branch,BirthDate,BloodGroup) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
int col = 1;
stmt.setString(col++, regno);
stmt.setDate(col++, new java.sql.Date(dt.getTime())); // assuming dt is a java.util.Date
(etc)
stmt.executeUpdate();
`enter code here`you can use prepared statement of insertion like..
Connection MyCon=null;
PreparedStatement Ps=null;
try{
myCon=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","student","student");
// these are string from where we can take inputs .
String Fname;
String Lname;
String email;
String department;
String Salary;
Fname=JOptionPane.showInputDialog(null,"Enter First Name");
Lname=JOptionPane.showInputDialog(null,"Enter Last Name");
email=JOptionPane.showInputDialog(null,"Enter Your Email");
department=JOptionPane.showInputDialog(null,"Enter Department Name");
Salary=JOptionPane.showInputDialog(null,"Enter Salary Name");
**String insertion="insert into employees"
+ "(first_name, last_name, email, department ,salary )"+"values "
+ "(?,?,?,?,?)";**
**Ps=(PreparedStatement) MyCon.prepareStatement(insertion);
Ps.setString(1,Fname);
Ps.setString(2,Lname);
Ps.setString(3,email);
Ps.setString(4,department);
Ps.setString(5,Salary);
Ps.executeUpdate();**
}catch(Exception e)
{
e.printtrace();
}
You Should use this template:
PreparedStatement pstmt = con .prepareStatement ("INSERT INTO TableName (ColumnNmae1, ColumnNmae2, ColumnNmae3...) VALUES (?,?,?...);
pstmt.setType(1, value);
pstmt.setType(2, value);
pstmt.setType(3, value);
etc.
in the prepared statemnt you need to use exactly the same amount oof question mark as the columns you manchined in the statment.
for each question mark you shoukd setValue, you need to choose the right set for eac value typr, there is setString setInt etc...
In your specific case it should look like that:
PreparedStatement pstmt = con .prepareStatement ("INSERT INTO TableName (RegistrationNo,Date,SeniorPerson...) VALUES (?,?,?...);
pstmt.setString(1, regno);
pstmt.setDate(2, Date);
pstmt.setString(3, SeniorPerson);
etc.
Yours is an example of how to NOT use PreparedStatement.
Here's a better idea:
// Here's a PreparedStatement to satisfy the person who downvoted.
PreparedStatement stmt = connection.prepareStatement();
// I might have missed a '?' - you should check it.
String qry= "INSERT INTO Registration1(RegistrationNo,Date,SeniorPerson,NativePlace,Kul,Gotra,KulSwami,ResidensialAddress,PinCode,STDcode,TelephoneNo,MobileNo,Email,Website,Education,Branch,BirthDate,BloodGroup) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
// Bind the variables here
stmt.executeUpdate(qry);
You should go through this carefully.

Problem with a prepared statement

I have this code:
Date start = new Date(Integer.parseInt(jTextField4.getText()), Integer.parseInt(jTextField16.getText()), Integer.parseInt(jTextField17.getText()));
Date end = new Date(Integer.parseInt(jTextField5.getText()), Integer.parseInt(jTextField18.getText()), Integer.parseInt(jTextField19.getText()));
statement = connection.createStatement();
preparedStatement1 = connection.prepareStatement("insert into sportmangg(customer_code,"
+ "sportman_code, start, finish, salary,amount,box salary,private salary, food salary, "
+ "other salary, bime salary, number) "
+ "values (? ,?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ?");
preparedStatement1.setString(1,jTextField15.getText());
preparedStatement1.setString(2, jTextField1.getText());
preparedStatement1.setDate(3, start);
preparedStatement1.setDate(4, end);
preparedStatement1.setInt(5, Integer.parseInt(jTextField6.getText()) );
preparedStatement1.setInt(6,Integer.parseInt(jTextField14.getText()) );
preparedStatement1.setInt(7, Integer.parseInt(jTextField7.getText()));
preparedStatement1.setInt(8, Integer.parseInt(jTextField8.getText()));
preparedStatement1.setInt(9, Integer.parseInt(jTextField9.getText()));
preparedStatement1.setInt(10, Integer.parseInt(jTextField11.getText()));
preparedStatement1.setInt(11, Integer.parseInt(jTextField10.getText()));
preparedStatement1.setInt(12, Integer.parseInt(jTextField20.getText()));
preparedStatement1.executeUpdate();
but it has this error:
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 'salary,private salary, food salary, other salary, bime salary, number) values ('' at line 1
What is the problem?
You really shouldn't have spaces in the field name. Try surrounding it with ``
Column names with spaces in them are a very bad idea.
If you must have them, surround them with backticks:
`private salary`
You missed ) in the last line of your SQL query so it should be:
+ " values (? ,?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ? )";
Maybe you can try this:
https://github.com/stuparmihailo/util4j/releases/tag/v1.0
It's some simple project and has nice way for creating statements:
String query = "INSERT INTO table VALUES (?,?,?,?,?,?,?)";
PreparedStatement stmt = con.prepareStatement(query);
StatementUtil.fill(stmt, 45, "text", 2, null, new Date(), false, 3.5);
You should replace private salary with private_salary and keep working with acceptable column name conventions.
column or table names should not have spaces. Join them by underscore. and make them upper case... these are not rules but accepted ways of working with DB objects. If names cannot be changed in the DB and you are stuck with something like some salary, then some salary should help.
mehdi;
I think what you have to do is all of this:
change names of
space-named columns (private salary,
food salary, other salary, bime
salary) either by replacing spaces by underscores
(recommended by naming conventions) or by
surrounding names with grave accent char:
`box salary`, `private salary`, `food salary`, `other salary`, `bime
salary`
Fix this line adding final parentheses
+ "values (? ,?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ?");
it must say:
+ "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
Finally I'd recommend to take out prepareStatement argument to a String or StringBuffer variable, say "sqlString" or something, so you can manipulate it more transparently. Something like this:
String sqlString = "";
sqlString += " insert into sportmangg";
sqlString += " (customer_code, sportman_code, start, finish,";
sqlString += " salary, amount, box_salary, private_salary,";
sqlString += " food_salary, other_salary, bime_salary, number)";
sqlString += " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
preparedStatement1 = connection.prepareStatement(sqlString);
(or if you use StringBuffer use append method)

Categories

Resources