prepared statement - java

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.

Related

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

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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

Java/MySQL - Retrieve ID from last record saved

Can anyone help me out please? I am trying to retrieve ID(primary key) at the time the record is created and set it to a textfield. Currently, all it returns is 1 all the time.
My current approach looks like this:
connection = Utilities.getConnection();
String sqlQuery = "INSERT INTO student_details (Name, Surname, Date_Of_Birth, Gender, Address, Post_Code, Mobile_Number)" + " VALUES (?, ?, ?, ?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setString(1, txtFirstName.getText().trim());
preparedStatement.setString(2, txtSurname.getText().trim());
preparedStatement.setString(3, String.valueOf(dpDateOfBirth.getValue()));
preparedStatement.setString(4, cbGender.getSelectionModel().getSelectedItem().toString());
preparedStatement.setString(5, txtAddress.getText().trim());
preparedStatement.setString(6, txtPostCode.getText().trim());
preparedStatement.setString(7, txtMobileNo.getText().trim());
preparedStatement.executeUpdate();
txtStudentID.setText(String.valueOf(preparedStatement.RETURN_GENERATED_KEYS));
Utilities.showInforMsg("Record Saved:", "Record has been saved.");
You should get the generated key via:
ResultSet rs = preparedStatement.getGeneratedKeys();
if (rs.next()) {
key = rs.getLong(1);
}
what you are doing with this line
txtStudentID.setText(String.valueOf(preparedStatement.RETURN_GENERATED_KEYS));
is setting the student id to the value of the constant of the Statement interface (see here https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#RETURN_GENERATED_KEYS)

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 (?, ?, ?, ?, ?, ?, ?, ?)";

Finishing MySQL prepared statement in JAVA

I am learning MySQL with JAVA, and don't understand prepared statements. Abstracting from I shall learn it, I want to ask for help in finishing this code to be "prepared stated" :-)
String stringQuery = "INSERT INTO banlist (name, reason, admin, time, temptime, IP) VALUES (testNick, testPowod, testAdmin, CURRENT_TIMESTAMP, NOW(), NULL);=?";
PreparedStatement statement = this.connection.prepareStatement( stringQuery );
statement.setString( 1, ); // after ' 1, ' we define what we want to get
ResultSet resultSet = statement.executeUpdate();
String stringQuery =
"INSERT INTO banlist (name, reason, admin, time, temptime, IP)"
+ " VALUES (?, ?, ?, CURRENT_TIMESTAMP, NOW(), NULL)";
PreparedStatement statement = this.connection.prepareStatement(stringQuery);
statement.setString(1, testNick);
statement.setString(2, testPowod);
statement.setString(3, testAdmin);
int inserted = statement.executeUpdate();
Read the JDBC tutorial.
Here's how I'd do it:
String insertQuery = "INSERT INTO banlist(name, reason, admin, time, temptime, IP) VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement statement = this.connection.prepareStatement( stringQuery );
statement.setString(1, name); // These values come from your code; dynamic
statement.setString(2, reason);
statement.setString(3, admin);
statement.setString(4, time);
statement.setString(5, tempTime);
statement.setString(6, ip);
int numRowsAffected = statement.executeUpdate();
Be sure to close your statement appropriately.

Unable to insert a row in Oracle with Java (JDBC) --> error ORA-00917: missing comma

I have a problem during an insert in Oracle using Java and JDBC. The error obtained is:
java.sql.SQLException: ORA-00917: missing comma
The data for the insert is taken from a form like a string and is parsed to the appropiated data type and then is saved in an object called edicio. That's all OK. Then, my intention is make an insert in the DB using the data of this object.
Here is the code of the DAO, where I'm making the insert:
public Edicio insertarCurs(Connection con, Edicio ed) throws SQLException {
PreparedStatement stm = null;
ResultSet rst = null;
// Insert
StringBuffer sql = new StringBuffer();
sql.append("INSERT INTO curs (id, nom, idarea, area, programa, datainici)");
sql.append(" VALUES (?, ?, ?, ?, ?, ?");
logger.info("Building insert works fine.");
try {
stm = con.prepareStatement(sql.toString());
// params
stm.setLong(1, ed.getIdEdicio());
stm.setString(2, ed.getNomEdicio());
stm.setLong(3, ed.getIdArea());
stm.setString(4, ed.getArea());
stm.setString(5, ed.getPrograma());
// Conversion from Java Date to SQL Date
java.sql.Date sqlDate = new java.sql.Date(ed.getDataInici().getTime());
logger.info("sqlDate before the insert is: "+ sqlDate); //0011-12-02
stm.setDate(6, sqlDate);
// Data and results commented
logger.info("Id edicio: "+ ed.getIdEdicio()); //6
logger.info("Nom edicio: "+ ed.getNomEdicio()); //test
logger.info("Id area: "+ ed.getIdArea()); //0
logger.info("Nom area: "+ ed.getArea()); //test
logger.info("Programa: "+ ed.getPrograma()); //test
logger.info("Data inici: "+ sqlDate); //2011-06-06
// We are going to execute the insert
int numRows = stm.executeUpdate();
// The program never reaches this point, fails doing the executeUpdate()
logger.info("Rows created: "+ numFiles);
...
The variable types are:
idEdicio = long
nomEdicio = String
idArea = long
area = String
programa = String
dataInici = Date
Can someone help me? Thank you in advance :)
Missing )
sql.append(" VALUES (?, ?, ?, ?, ?, ?");
should be
sql.append(" VALUES (?, ?, ?, ?, ?, ?)");
sql.append(" VALUES (?, ?, ?, ?, ?, ?)");
^--- missing parenthesis

Categories

Resources