Related
My app allows users to create an account (stored in database) and place orders.
When a client registers himself, I want to generate a primary key named CLIENT_CODE to identify him, starting from x value and increment it with y value. (I'm using oracle 11g atm)
I've tried this so far:
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String fname = jTextField9.getText();
String lname = jTextField10.getText();
String city = jTextField11.getText();
String street = jTextField13.getText();
String number = jTextField14.getText();
String userClient = jTextField15.getText();
String pass1 = String.valueOf(jPasswordField5.getPassword());
String pass2 = String.valueOf(jPasswordField6.getPassword());
if(verifyFields()){
if(!checkUsername(userClient)){
OraclePreparedStatement ps;
OracleResultSet rs;
String registerClient = "insert into CLIENT (FNAME_CL, LNAME, CITY, STREET, NUMBER, MONEY, CLIENT_CODE, USER_CLIENT, PASS) values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
try {
ps = (OraclePreparedStatement) JavaConnectDb.ConnectDb().prepareStatement(registerClient);
ps.setString(1, fname);
ps.setString(2, lname);
ps.setString(3, city);
ps.setString(4, street);
ps.setString(5, number);
ps.setDouble(6, 0.0);
ps.setInt(7, ???); <--- here should be the generated primary key
ps.setString(8, userClient);
ps.setString(9, pass1);
if(ps.executeUpdate() != 0){
JOptionPane.showMessageDialog(null, "Account created!");
} else{
JOptionPane.showMessageDialog(null, "Error: Check your info");
}
} catch (SQLException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Don't do it in Java; handle the primary key value creation in the database using a sequence:
CREATE SEQUENCE CLIENT__CLIENT_CODE__SEQ
START WITH 1
INCREMENT BY 1
Then just use your sequence in the INSERT statement and use the RETURNING clause to get the generated value as an OUT parameter of your prepared statement.
insert into CLIENT (
FNAME_CL,
LNAME,
CITY,
STREET,
NUMBER,
MONEY,
CLIENT_CODE,
USER_CLIENT,
PASS
) values (
?,
?,
?,
?,
?,
?,
CLIENT__CLIENT_CODE__SEQ.NEXTVAL,
?,
?
) RETURNING CLIENT_CODE INTO ?
If you were using Oracle 12c then you could use GENERATED AS IDENTITY in the table's CREATE DDL statement to generate the values without creating a separate sequence.
I want to insert 5 datas into one SQL table, the last four of which are already working and fine, but the first one should be from another table, a String, giving an Int to the table in which im inserting it. And this is my solution so far. However i'm still getting an error:
"The index 5 is out of range."
PreparedStatement stmt = connection.prepareStatement("INSERT INTO RECORDS (LocationId, RecId, RecValues, YearTime, HourTime) VALUES " +
"((SELECT LocationId from Locations where Location_name = 'Mic HR1'), ?, ?, ?, ?)");
stmt.setInt(1,1);
stmt.setInt(2, recid);
stmt.setInt(3, inputData);
stmt.setDate(4, sqlDate);
stmt.setTime(5, Time.valueOf(dtf.format(now)));
stmt.executeUpdate();
Actually you have only four parameters defined on your query, because LocationId is being calculated by the inner select you provided. That's why you are getting the error.
Try this:
PreparedStatement stmt = connection.prepareStatement("INSERT INTO RECORDS (LocationId, RecId, RecValues, YearTime, HourTime) VALUES " +
"((SELECT LocationId from Locations where Location_name = 'Mic HR1'), ?, ?, ?, ?)");
stmt.setInt(1, recid);
stmt.setInt(2, inputData);
stmt.setDate(3, sqlDate);
stmt.setTime(4, Time.valueOf(dtf.format(now)));
stmt.executeUpdate();
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...
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.
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.