how to auto generate id in java textfield from mysql - java

What I've tried:
try
{
PreparedStatement pstat = con.prepareStatement("insert into student_info values (?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
pstat.setInt(1, Integer.parseInt(txtId.getText()));
pstat.setString(2, txtFName.getText());
pstat.setString(3, txtLName.getText());
pstat.setString(4, gender);
int result = pstat.executeUpdate();
if(result > 0)
{
JOptionPane.showMessageDialog(null,"Data Inserted Succesfully !!!");
txtId.setText("");
txtFName.setText("");
txtLName.setText("");
bg.clearSelection();
ResultSet rs = pstat.getGeneratedKeys();
int newId= -1;
if(rs != null && rs.next())
{
newId = rs.getInt(1);
txtId.setText(String.valueOf(newId));
}
}
}
What I want:
The new id to be displayed in the textbox
What doesn't happen:
The new id doesnt get displayed in textfield..

Make this changes to your code:
PreparedStatement pstat = con
.prepareStatement("insert into student_info (firstname,lastname,gender)
values (?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS); // omit id column
pstat.setString(1, txtFName.getText());
pstat.setString(2, txtLName.getText());
pstat.setString(3, gender);
int result = pstat.executeUpdate();
// now got fetch the generated id

Related

How to get all generated ID's while insert bulk rows

String sql = "YOUR INSERT STATEMENT HERE";
PreparedStatement ps = conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
ps.execute();
ResultSet rs = ps.getGeneratedKeys();
int generatedKey = 0;
while (rs.next()) {
int generatedKey = rs.getInt(1);
System.out.println("Inserted record ID: " + generatedKey);
}
Above statement returning only last inserted row ID only.
How to get All generated ID's while inserting bulk values ?

if data not found in database insert data else update data

pstmt = conn.prepareStatement(SLCMQueryConstant.SELECT_ROLE_FOR_MAP);
pstmt.setInt(1, roleid);
pstmt.setInt(2, pageid);
rs = pstmt.executeQuery();
if (rs.next()) {
PageDTO PageDTo = new PageDTO();
PageDTo.setRolePageMapID(rs.getInt("Role_Page_Map_ID"));
System.out.println(rs.getInt("Role_Page_Map_ID"));
if (rs.getInt("Role_Page_Map_ID") == 0) {
String query = SLCMQueryConstant.INSERT_INTO_ROLE_PAGE_MAP;
int count = 1;
pstmt = conn.prepareStatement(query);
pstmt.setInt(count++, pageid);
pstmt.setInt(count++, roleid);
pstmt.executeUpdate();
System.out.println(conn.getAutoCommit());
conn.commit();
} else {
String query = SLCMQueryConstant.REUPDATE_INTO_ROLE_PAGE_MAP;
int count = 1;
pstmt = conn.prepareStatement(query);
pstmt.setInt(count++, pageid);
pstmt.setInt(count++, roleid);
pstmt.executeUpdate();
System.out.println(conn.getAutoCommit());
conn.commit();
}
}
in particular code,if table doesn't found entry corresponds to roleid and pageid
then while is not executing if an entry found then update is happen.
How to do insert operation if table doesn't found role_Page_Map_ID?
if (rs.next()) {
//Do something
}
else {
INSERT
}

Verify if the row is not available in mySQL table

I want message (the row is not available in the stock) if row is not available in the database. I try the following code but the error....!
//Code
try {
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int count = 0;
while (rs.next()){
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "Item is available in Stock"
} else {
JOptionPane.showMessageDialog(null, "ID:" + txtS.getText() + "is not available in the Stock please update the Stock");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
// error....
java.sql.SQLException: No value specified for parameter 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
.....
.....
....
....
Please help.....
You are not setting the value for the ? in your SELECT statement.
Given that it's an ID I will assume it is an int.
You need:
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, value);
ResultSet rs = ps.executeQuery();
EDIT
Try changing your methodology to this:
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, value);
ResultSet rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Item is available in Stock"
}
else {
JOptionPane.showMessageDialog(null, "ID:" + txtS.getText() + "is not available in the Stock please update the Stock");
}
Thanks # Matt for help
i got a perfect Answer by using this code......
try {
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, txtS.getText());
ResultSet rs = ps.executeQuery();
int count = 0;
while (rs.next()){
// code update here
count = rs.getInt(1);
// count = count + 1;
}
if (count == 1) {

Exhausted ResultSet Issue with Servlet Oracle

Every time I run this code it gives me an exhauset resultset error. Im not sure what Im doing wrong but Ive tried removing the .next(); code for either one or all resultsets and then the error given is the ResultSet next wasnt called.
Im not sure what Im doing wrong. Just curious what people might think the issue could be? Ive done similar earlier in my servlet code but only used 1 statement and then 1 prepared statement. This time Im using 2 statements and 1 prepared statement.
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
rs11.next();
ResultSet rs12 = stmt.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
rs12.next();
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
int olo1 = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)");
pstmt1.clearParameters();
pstmt1.setInt(1,olo);
pstmt1.setInt(2,olo1);
ResultSet rs1 = pstmt1.executeQuery();
rs1.next();
Some ideas on your code (in comments)
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
//Check if you HAVE a line here!
if(!rs11.next()) {
System.out.println("No Recipe Found");
}
//Use stmt1 - that's why you created it?!
ResultSet rs12 = stmt1.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
if(!rs12.next()) {
System.out.println("No Ingredient Found");
}
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
//Read Ingredient from rs12 -> that's where you selected it into
int olo1 = ((Number) rs12.getObject(1).intValue(); //convert resultset value to int
While this might point you into the right direction for solving the current issue, you should consider learning about clean code.
Consider this code making use of try-with-resource, refactored out some methods, using prepared statements.
//Replace exiting code
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
int recipieId = getRecipeId(con, opt1);
int ingredientId = getIngredientId(con, ingr1);
if(recipeId > 0 && ingredientId > 0) {
//Process result
insertRecLnk(con, recipeId, ingredientId);
} else {
System.out.println("No INSERT");
}
//Helper functions
protected int getRecipeId(Connection con, String rec) {
try(PreparedStatement st = con.prepareStatement("SELECT recipe_ID FROM GM_Recipes WHERE rec_name=?")) {
st.setString(1, rec);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Recipe Found");
return -1;
}
protected int getIngredientId(Connection con, String ing) {
try(PreparedStatement st = con.prepareStatement("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name=?")) {
st.setString(1, ing);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Ingredient Found");
return -1;
}
protected void insertRecLnk(Connection con, int rId, int iId) {
try(PreparedStatement ps = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)")) {
ps.setInt(1, rId);
ps.setInt(2, iId);
ps.executeUpdate();
} catch(SQLException e) {
e.printStackTrace();
}
}

jdbc help translating mapping char to string when updating a database

I am trying to map a particular character to show the full word so in this code below I have a translate method, a select method that is selecting from the remote database and update method that updates those column to my local database.
My remote database has a column called profile_ind this columns only has single chars B,C,F,P,S,W in the data, and once I do the update I want to be able to translate it to the full word only without the chars. B = BENIGN, C = CUSTOMER, F = FRAME, P = PPCOS, S = STANDARD, W = W-RED
And in my update method I want to call that translate method. cos_profile_type is the column on my local database that I want to update to either BENIGN, CUSTOMER, FRAME,PPCOS,STANDARD,W-RED depending on profile_ind column in the remote db. How can I implement it ? how can i call that translate method in the update method when I set the ? in that statement.
public static String translate(String indicator) throws Exception {
if (indicator == null || indicator.length() == 0) return "";
if (indicator.equals("B")) return "BENIGN";
if (indicator.equals("C")) return "CUSTOMER";
if (indicator.equals("F")) return "FRAME";
if (indicator.equals("P")) return "PPCOS";
if (indicator.equals("S")) return "STANDARD";
if (indicator.equals("W")) return "W-RED";
System.out.println(indicator);
return "";
}
public static void selectRecordsIcore() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Statement statement = null;
java.util.Date date= new java.util.Date();
String selectTableSQL = "SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag, profile_ind from COS_PROFILE"
+ " WHERE profile_id >= ? AND profile_id <= ? ;";
try {
dbConnection = getInformixConnection(); //connects to ICORE database
System.out.println("ICORE Select Statement: " + selectTableSQL);
//Gets the max profile_id record
statement = dbConnection.createStatement();
ResultSet r = statement.executeQuery("SELECT max(profile_id) AS rowcount FROM COS_PROFILE");
r.next();
int maxCount = r.getInt("rowcount");
System.out.println("COS_PROFILE table has " + maxCount + " row(s).");
preparedStatement = dbConnection.prepareStatement(selectTableSQL);
preparedStatement.setInt(1, 1);
preparedStatement.setInt(2, maxCount);
// execute select SQL statement
rs = preparedStatement.executeQuery();
updateRecordIntoBids();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("inside the finally block ICORE " + new Timestamp(date.getTime()));
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
System.out.println("ICORE Statement Connection is closed");
}
if (preparedStatement != null) {
preparedStatement.close();
System.out.println("ICORE PreparedStatement Connection is closed");
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database ICORE Connection is closed");
}
}
}
private static void updateRecordIntoBids() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Statement statement = null;
dbConnection = getOracleConnection(); //connects to BIDS database
java.util.Date date= new java.util.Date();
//Gets the max profile_id record
statement = dbConnection.createStatement();
dbConnection.setAutoCommit(false);
ResultSet r = statement.executeQuery("SELECT count (*) AS rowcount FROM traffic_profile_temp");
r.next();
int maxCount = r.getInt("rowcount");
System.out.println("Traffic_profile_temp table before update has " + maxCount + " row(s).");
String updateTableSQL =
"UPDATE traffic_profile_temp SET pe_ingress_flag = ?, "
+ " pe_egress_flag = ?,"
+ " ce_ingress_flag = ?,"
+ " ce_egress_flag = ?, "
+ " cos_profile_type = ? "
+ " WHERE traffic_profile_id = ? ";
// execute update SQL statement
System.out.println("BIDS Update Statement: " + updateTableSQL);
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
System.out.println("Updating Bids Database in process ...");
try {
int rowCount = 0;
int expectedId = 1;
int first = 0;
while (rs.next()) {
String ingressflag = rs.getString("ingress_flag"); //BIDS column is pe_ingress_flag
String egressflag = rs.getString("egress_flag"); //BIDS column is pe_egress_flag
String ceingressflag = rs.getString("ce_ingress_flag"); //BIDS column is ce_ingress_flag
String ceegressflag = rs.getString("ce_egress_flag"); //BIDS column is ce_egress_flag
String profileind = rs.getString("profile_ind"); //BIDS column is cos_profile_type
int profileid = rs.getInt("profile_id"); //BIDS column is traffic_profile_id
preparedStatement.setString(1, ingressflag);
preparedStatement.setString(2, egressflag);
preparedStatement.setString(3, ceingressflag);
preparedStatement.setString(4, ceegressflag);
preparedStatement.setString(5, profileind);
preparedStatement.setInt(6, profileid);
preparedStatement.addBatch();
rowCount++;
if(expectedId == profileid){
if(first == 0){
first = expectedId-1;
}
}
if(expectedId != profileid){
if(first > 0){
System.out.println ("Profile id "+first+" to "+(expectedId-1)+" update.");
first = 0;
}
System.out.println ("Profile id "+expectedId+" to "+(profileid-1)+" missing.");
expectedId = profileid;
}
expectedId++;
}
if(first > 0){
System.out.println("Profile id "+first+" to "+(expectedId-1)+" update.");
first = 0;
}
preparedStatement.executeBatch();
dbConnection.commit();
System.out.println("Record(s) Updated : " + rowCount + new Timestamp(date.getTime()));
} catch (SQLException e) {
System.out.println("Update records Failed!! " + e.getMessage());
} finally {
System.out.println("inside the finally block BIDS" + " timestamp " + new Timestamp(date.getTime()));
if (statement != null) {
statement.close();
System.out.println("BIDS Statement Connection is closed");
}
if (preparedStatement != null) {
preparedStatement.close();
System.out.println("BIDS PreparedStatement Connection is closed");
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database BIDS Connection is closed");
}
}
}

Categories