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
}
Related
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 ?
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) {
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();
}
}
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
hello i am trying to retrieve data in two result set. then i have store in both resultset to String Array, after this process i have to store my String array to another table how to so this kindly tell me..
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.
getConnection("jdbc:mysql://localhost:3306/lportal", "root", "ubuntu123");
PreparedStatement stmt = (PreparedStatement) con.
prepareStatement("SELECT * FROM Testi_Testimonial where subject = ?");
stmt.setString(1, search);
stmt.execute();
rs = (ResultSet) stmt.getResultSet();
while (rs.next()) {
anArray[i] = rs.getString("subject");
System.out.println(anArray[i]);
i++;
count++;
}
PreparedStatement stmt1 = (PreparedStatement) con.
prepareStatement("SELECT * FROM Testi_Testimonial where subject != ?");
stmt1.setString(1, search);
stmt1.execute();
rs1 = (ResultSet) stmt1.getResultSet();
while (rs1.next()) {
anArray[i] = rs1.getString("subject");
System.out.println(anArray[i]);
i++;
count++;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("problem in connection");
}
Please tell me how should I store my array to Temp table? my "Temp" table has column subject I want to store myArray to subject column... kindly tell me how to do this.
try this after getting resultset in rs:
PreparedStatement st = (PreparedStatement) con.prepareStatement("insert into temp values(?)");
i=0;
while(rs.next())
{
st.setString(1,anArray[i]);
st.executeUpdate();
i++;
}
You just iterate the arrayList. You got the subject List as respective.
public class TestArrayList {
public static void main(String[] args) {
/*create two arrayList*/
List<String> tempOneList = new ArrayList<String>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay", "root", "root");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM subjecttable");
while (res.next()) {
tempOneList.add(res.getString("subject"));
}
ResultSet resOne = st.executeQuery("SELECT * FROM subjecttabletwo");
while (resOne.next()) {
tempOneList.add(resOne.getString("subject"));
}
System.out.println("temp/List>>--" + tempOneList.size());
for(int i=0;i<tempOneList.size();i++){
System.out.println(tempOneList.get(i));
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("problem in connection");
}
}
}
PreparedStatement ps =
(PreparedStatement) con.prepareStatement("insert into temp values(?)");
j=0;
while(rs.next())
{
ps.setString(1,anArray[j]);
ps.executeUpdate();
j++;
}