Oracle primary key generator in Java - java

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.

Related

Parameter index out of range (1 > number of parameters, which is 0). output when attempting to save information to database

I created a small program where the user must input data into text fields and select options from combo boxes. I created a database using XAMPP and created the corresponding tables for the program through the web browser.
The database is called activitydb and the table that's responsible for storing the data from the program is called userdata.
The first column in the table is called UserID and is an int that auto increments every time a new entry is added.
The rest are all varchars with varying maximum lengths.
This is currently the source code of the program:
Connection con = null;
Statement st = null;
try {
// activitydb = database name
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/activitydb?zeroDateTimeBehavior=convertToNull", "root", "");
st = con.createStatement();
// userdata = table name
String sqlconn = "INSERT INTO userdata (UserID, LastName, FirstName, MiddleName, Email, Sex, HomeAddress, City, CPUBrand, ComputerType, HardwareSpecs, GPUBrand, GPUType, GPUVRAM)";
PreparedStatement prdStmt = con.prepareStatement(sqlconn);
// Input of variable data into corresponding database table
// First table will be declared as null as it is an Integer designed with an Auto Increment
prdStmt.setString(1, null);
prdStmt.setString(2, jTextLastName.getText());
prdStmt.setString(3, jTextFirstName.getText());
prdStmt.setString(4, jTextMiddleName.getText());
prdStmt.setString(5, jTextEmail.getText());
prdStmt.setString(6, jComboBoxSex.getSelectedItem().toString());
prdStmt.setString(7, jTextHomeAddress.getText());
prdStmt.setString(8, jTextCity.getText());
prdStmt.setString(9, jComboBoxCPUBrand.getSelectedItem().toString());
prdStmt.setString(10, jComboBoxComputerType.getSelectedItem().toString());
prdStmt.setString(11, jComboBoxHardwareSpecs.getSelectedItem().toString());
prdStmt.setString(12, jComboBoxGPUBrand.getSelectedItem().toString());
prdStmt.setString(13, jComboBoxGPUType.getSelectedItem().toString());
prdStmt.setString(14, jComboBoxGPUVRAM.getSelectedItem().toString());
// Do this if something goes wrong
} catch (SQLException err) {
// Print error message to console for diagnosis
System.out.println(err.getMessage());
}
For the combo boxes, I've used getSelectedItem().toString() to have the data found inside stored as a String.
Clicking the button will make the program do nothing but print this in the console:
Parameter index out of range (1 > number of parameters, which is 0).
You are missing the place holders ? to put the values, your query should be :
String sqlconn = "INSERT INTO userdata (UserID, LastName, FirstName, MiddleName," +
" Email, Sex, HomeAddress, City, CPUBrand, ComputerType, HardwareSpecs," +
" GPUBrand, GPUType, GPUVRAM) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

How to use getParameterNames() value

I am getting parameters name and values from from UI to my servlet using getParameterNames. Now I want to use those values to run my query but I don't know how to do that I am getting errors while doing that
What I am doing
From Ui having Dynamic stars so getting values using getParameterNames(), then try to use that values.
If user selects 5 stars I am getting its parameter and its values as 1 because excellent is defined as 1 in my data base very good as 2 and so on to poor as 5.
So I am getting values as after click on save
Parameter Name is 'Quality Of Food' and Parameter Value is '3'
Parameter Name is 'Cleanliness' and Parameter Value is '3'
Parameter Name is 'Service' and Parameter Value is '3'
Parameter Name is 'Staf Behavior' and Parameter Value is '3'
Parameter Name is 'Ambience' and Parameter Value is '2'
Now I am running a query in my Java servlet doPost class to get respective attributes to values. For example, for value 2 attribute name is excellent like that.
After that I have to insert all this data into my db.
The main thing is all the stars are dynamic as coming from database as JSON so it can vary currently I am having 5 attributes of 5-5 stars to show on UI on click of submit getting data in back end
My code
Connection con = null;
Statement statement = null;
java.util.Date dateUtil = new Date();
java.sql.Date dateSql = new java.sql.Date(dateUtil.getTime());
java.sql.Timestamp timestamp = new Timestamp(dateUtil.getTime());
try {
con = DBConnection.createConnection();
statement = con.createStatement();
Enumeration en = request.getParameterNames();
while (en.hasMoreElements()) {
Object objOri = en.nextElement();
String param = (String) objOri;
String value = request.getParameter(param);
System.out.println("Parameter Name is '" + param + "' and Parameter Value is '" + value + "'");
String getSql = "select ATTRIBUTENAME from FEEDBACKATTRUBUTES where POSITIONNO=" + value
+ " and ATTRIBUTETYPE ='STARRING'";
String updateSql = "INSERT INTO CUSTOMERFEEDBACK (CUSTOMERID, CUSTOMERNAME, BILLNO, BILLDATE, ATTRIBUTE1, ATTRIBUTE2, ATTRIBUTE3, ATTRIBUTE4, ATTRIBUTE5, ATTRIBUTE6, ATTRIBUTE7, ATTRIBUTE8, ATTRIBUTE9, ATTRIBUTE10, REMARKS, CREATEDTIMESTAMP, SMSSENT)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
ResultSet resultSet = statement.executeQuery(getSql);
while (resultSet.next()) {
String attributeName = resultSet.getString("ATTRIBUTENAME");
PreparedStatement ps = con.prepareStatement(updateSql);
ps.setString(1, "123456");
ps.setString(2, "Dheeraj");
ps.setString(3,"-");
ps.setDate(4,dateSql);
ps.setString(5, param+":"+attributeName); //how can i insert these values
ps.setString(6, param+":"+attributeName);
ps.setString(7, param+":"+attributeName);
ps.setString(8, param+":"+attributeName);
ps.setString(9, param+":"+attributeName);
ps.setString(10, param+":"+attributeName);
ps.setString(11, param+":"+attributeName);
ps.setString(12, param+":"+attributeName);
ps.setString(13, param+":"+attributeName);
ps.setString(14, param+":"+attributeName);
ps.setString(15, "remark");
ps.setTimestamp(16, timestamp);
ps.setString(17, "N");
ps.addBatch();
ps.executeBatch();
}
}
} catch (SQLException e) {
System.out.println("SQL EXCPTION 91");
e.printStackTrace();
}
As in my code you can check from ps.setString(5, param+":"+attributeName); //how can I insert these values this line param and value (attribute name I am inserting) but I have got only 5 attributes values from UI for all others I have to insert -.
My main issue is currently I am having only five attributes on my UI but here in Java class insert query I have to insert 5 and other as null or -.
For better understanding, this is my UI.
You need to modify the sequence of the process, first you need to store the params and their values locally and then add them to the prepared statement before executing it.
Here is a modified version of your code that does it:
Connection con = null;
Statement statement = null;
java.util.Date dateUtil = new Date();
java.sql.Date dateSql = new java.sql.Date(dateUtil.getTime());
java.sql.Timestamp timestamp = new Timestamp(dateUtil.getTime());
try {
con = DBConnection.createConnection();
statement = con.createStatement();
Enumeration en = request.getParameterNames();
LinkedHashMap<String, Integer> evaluation = new LinkedHashMap<>();
HashMap<Integer,String > classifications = new HashMap<>();
String getSql = "select ATTRIBUTENAME,POSITIONNO from FEEDBACKATTRUBUTES where ATTRIBUTETYPE ='STARRING'";
ResultSet resultSet = statement.executeQuery(getSql);
while (resultSet.next()) {
classifications.put(resultSet.getInt("POSITIONNO"),resultSet.getString("ATTRIBUTENAME"));
}
while (en.hasMoreElements()) {
Object objOri = en.nextElement();
String param = (String) objOri;
String value = request.getParameter(param);
System.out.println("Parameter Name is '" + param + "' and Parameter Value is '" + value + "'");
evaluation.put(param,Integer.parseInt(value));
}
String updateSql = "INSERT INTO CUSTOMERFEEDBACK (CUSTOMERID, CUSTOMERNAME, BILLNO, BILLDATE, ATTRIBUTE1, ATTRIBUTE2, ATTRIBUTE3, ATTRIBUTE4, ATTRIBUTE5, ATTRIBUTE6, ATTRIBUTE7, ATTRIBUTE8, ATTRIBUTE9, ATTRIBUTE10, REMARKS, CREATEDTIMESTAMP, SMSSENT)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(updateSql);
ps.setString(1, "123456");
ps.setString(2, "Dheeraj");
ps.setString(3,"-");
ps.setDate(4,dateSql);
Iterator<Map.Entry<String, String>> evaluationIterator = evaluation.entrySet().iterator();
int i = 5;
while (i<15) {
if(evaluationIterator.hasNext()){
Map.Entry<String, String> entry = evaluationIterator.next();
ps.setString(i, entry.getKey()+":"+classifications.get(entry.getValue()));
}
else{
ps.setString(i, "");
}
i++;
}
ps.setString(15, "remark");
ps.setTimestamp(16, timestamp);
ps.setString(17, "N");
ps.addBatch();
ps.executeBatch();
} catch (SQLException e) {
System.out.println("SQL EXCPTION 91");
e.printStackTrace();
}
please let me know if this works for you, note that the code is not tested and could contain errors.

JDBC Prepared Statement Syntax Error

I am trying to insert into a vehicle table using a prepared statement. This is the table shown in PHPMyAdmin.
This is my java code
try {
String sql = "INSERT INTO vehicle (vin, serial, make, model, year, reg.no., status) VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, vin);
statement.setString(2, serial);
statement.setString(3, make);
statement.setString(4, model);
statement.setInt(5, 10);
statement.setInt(6, 17);
statement.setString(7, status);
System.out.println(statement.toString());
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}
} catch (Exception ex) {
System.out.println(ex);
}
and this is the resulting error
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' status) VALUES ('dfg', 'dfgfg', 'fg', 'sd564', 10, 17, 'dsf')' at line 1
I am clueless. Does it have to do with me not passing a value for the primary key "id" column in the table?
reg.no. isn't a valid column name. If you really need to use it, you should quote it:
INSERT INTO vehicle (vin, serial, make, model, year, `reg.no.`, status)
-- Here ---------------------------------------------^-------^
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)

SQLException, No value for parameter 5

I'm using a UI that I've built to get input and MySQL to store the data locally. However, when I use the MySQL insert function, I'm encountering the following error:
java.sql.SQLException: No value specified for parameter 5
I only have four input fields, and four columns in the table; however, my debugger says I have seven value parameters. Here is the Insert statement:
private static final String GLInsert = "INSERT INTO gl_maint(GL_MAINT_NUM, GL_MAINT_NAME, GL_TYPE, BAL_FORWARD)"
+ "VALUES(?, ?, ?, ?) ON DUPLICATE KEY UPDATE "
+ "GL_MAINT_NAME = ?, GL_MAINT_TYPE = ?, BAL_FORWARD = ?";
And the preparedStatement method:
public void InsertGL(String ANstr, String ANAstr, String AIstr, double balfor) {
try {
conn = DriverManager.getConnection(ConnCheck, user, password);
GL_List = FXCollections.observableArrayList();
st = conn.prepareStatement(GLInsert);
st.setString(1, ANstr);
st.setString(2, ANAstr);
st.setString(3, AIstr);
st.setDouble(4, balfor);
st.executeUpdate();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(GLMaintAcct.class.getName()).log(Level.SEVERE, null, ex);
}
}
The issue is you have 7 parameters according to this query:
"INSERT INTO gl_maint(GL_MAINT_NUM, GL_MAINT_NAME, GL_TYPE, BAL_FORWARD)"
+ "VALUES(?, ?, ?, ?) ON DUPLICATE KEY UPDATE "
+ "GL_MAINT_NAME = ?, GL_MAINT_TYPE = ?, BAL_FORWARD = ?";
But you have just 4 value assigned like below:
st.setString(1, ANstr);
st.setString(2, ANAstr);
st.setString(3, AIstr);
st.setDouble(4, balfor);
You should add other 3 values like this providing their types:
st.setString(5, value5);
st.setDouble(6, value6);
st.setString(7, value7);

Categories

Resources