Update query for java JDBC +mysql database - java

I'm trying to run update query on table doctors. The primary key of the table is defined as a composite primary key (deptid, docid). What I'm trying to do is to update field designation, qualification and time based on deptid and docid (by another query).
I believe I'm doing something very silly but I'm not able to find it. Can someone help?
String did= request.getParameter("text1");
String dname = request.getParameter("text2");
String desig = request.getParameter("text3");
String qualification = request.getParameter("text4");
String time = request.getParameter("text5");
String className = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://192.168.10.13";
String user = "root";
String password = "";
PreparedStatement ps;
ResultSet rs;
try {
Class.forName(className);
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/webhospital","root","");
// PreparedStatement prepStmt = (PreparedStatement) conn.prepareStatement("Select * from tbl_userinfo");
ps = (com.mysql.jdbc.PreparedStatement) con.prepareStatement("update doctors set Designation=?,Qualification=?,Time= ? where deptid =? and docid IN(select docid from doctors where doctorname='dname';)");
ps.setString(1, did);
ps.setString(3,desig);
ps.setString(4,qualification);
ps.setString(5,time);
ps.executeUpdate();
} catch (ClassNotFoundException cx) {
out.println(cx);
} catch (SQLException ex) {
Logger.getLogger(MysqlInsertServlet.class.getName()).log(Level.SEVERE, null, ex);
}

ps = (com.mysql.jdbc.PreparedStatement) con.prepareStatement("update doctors set Designation=?,Qualification=?,Time= ? where deptid =? and docid IN(select docid from doctors where doctorname='dname';)");
ps.setString(1, did);
ps.setString(3,desig);
ps.setString(4,qualification);
ps.setString(5,time);
You have 4 question mark but set in wrong order why you don't set like :
ps.setString(1, desig);
ps.setString(2,qualification);
ps.setString(3,time);
ps.setString(4,deptId);
Supplying Values for PreparedStatement Parameters
You must supply values in place of the question mark placeholders (if
there are any) before you can execute a PreparedStatement object. Do
this by calling one of the setter methods defined in the
PreparedStatement class. The following statements supply the two
question mark placeholders in the PreparedStatement named updateSales:
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
The first argument for each of these setter methods specifies the
question mark placeholder. In this example, setInt specifies the first
placeholder and setString specifies the second placeholder.

One change required in your query is
"where doctorname='dname';)" ==>> "where doctorname='"+dname+"';)"

I think without editing your code it is good to show you an simple example.
PrintWriter out = response.getWriter();
String Title = request.getParameter("Title");
String Artist = request.getParameter("Artist");
String Country = request.getParameter("Country");
String price = request.getParameter("price");
String Year = request.getParameter("Year");
try {
//loading driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", "app");
PreparedStatement ps = con.prepareStatement("update COMPACT_DISK set TITLE=?,ARTIST=?,COUNTRY=?,PRICE=?,YEARS=? where TITLE=?");
ps.setString(1, Title);
ps.setString(2, Artist);
ps.setString(3, Country);
ps.setString(4, price);
ps.setString(5, Year);
ps.setString(6, Title);
int i = ps.executeUpdate();
if (i > 0) {
out.println("Compact disk successfully inserted");
}
} catch (Exception se) {
out.println("Error Occured : \n" + se.getLocalizedMessage());
se.printStackTrace();
}

Related

Insert query not executing

I want to insert the product the user selected into a table called cart which has two columns: cart_id and item_id_FK both are foreign keys. User_id and id are passed in the constructor and then inserted into cart_id and item_id_fk.
No errors are showing in the code, I double checked the connection username and password, everything works fine except for the cart table.
I tried putting a try and catch statement inside and repeating the steps it didn't work.
if (e.getSource()==AddToCartBtn)
{
//Check to see if item is available
String SizeSelection;
SizeSelection = SizeCmbx.getSelectedItem().toString();
String DBURL ="JDBC:MySql://localhost:3306/shoponline?useSSL=true";
String USER ="root";
String PASSWORD ="12345678";
try {
Connection con = DriverManager.getConnection(DBURL, USER, PASSWORD);
String sql2 = String.format("select itemid,size,productid_fk from items where size='%s' and productid_fk=%d",SizeSelection,id);
PreparedStatement statement = con.prepareStatement(sql2);
ResultSet result = statement.executeQuery(sql2);
String sql3 = "insert into cart (CartID, ItemID_FK)" + " values (?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(sql3);
preparedStmt.setInt(1, user_ID);
preparedStmt.setInt(2, id);
if(result.next())
{
//if item is available
// execute the preparedstatement
preparedStmt.execute();
}//end if
con.close();
}// end try
catch (SQLException ex){
ex.printStackTrace();
}//end catch
Change executeQuery to executeUpdate:
executeQuery(sql3)
to
executeUpdate(sql3)
I believe integers don't need the ' ' around them to be inserted, you may try removing those as well. It may be mistaking them as characters or something similiar.
Otherwise if neither of those above fixes work, try something like this:
String query = "insert into cart (CartID, ItemID_FK)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, xInt);
preparedStmt.setInt(2, yInt);
// execute the preparedstatement
preparedStmt.execute();
conn.close();

how to pass the id value using name from one table to another table and store the information to database [duplicate]

This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 4 years ago.
Sql query how to pass the id from department table using the department name to the user table using the department id
here in department table dept_id is primary key
and dept_id in user table is foreign key
how to select the dept_id using department_name from the department table and store the value in the user table
try{
Connection con = DBconnect.getConnection();
//selecting the dpartment
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
String s11=comboboxdeptid.getItems().toString();
ResultSet rs=ps.executeQuery();
if(rs.next()==true)
{
if(rs.getString("DEPARTMENT_NAME").equals(comboboxdeptid.getSelectionModel().toString()))
rs.getString("DEPARTMENT_CODE");
}
//second stmt
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
String s12 = nameid.getText();
String s13 = Firstnameid.getText();
String s14 = Lnameid.getText();
String s15 = desigid.getText();
String s16 = comboboxdeptid.getItems().toString();
String s17 = addrsid.getText();
String s18 = passwordid.getText();
ps.setString(1, s12);
ps.setString(2, s13);
ps.setString(3, s14);
ps.setString(4, s15);
ps.setString(5, s17);
ps.setString(6, s18);
ps.setString(7, s11);
ps.setString(8, "abc");
ps.execute();
ResultSet rs1=ps1.executeQuery();
//third stmt
String sql2 = "update security_qa_info set SECURITY_QUESTION=?, SECURITY_ANSWER=? where USER_ID=?";
PreparedStatement ps2 = con.prepareStatement(sql2);
String s19 = securityquestionid.getSelectionModel().getSelectedItem().toString();
String s20 = answerid.getText();
while(rs2.next()==true)
{
if(rs2.getString("USER_NAME").equals(nameid.getText()))
{
rs2.getString("USER_ID");
ps2.setString(1, s16);
}
}
ps2.setString(2, s19);
ps2.setString(3, s20);
ps2.executeUpdate();
showMessageDialog(null, "Registration Successful");
}catch(Exception e){
// showMessageDialog(null, e);
e.printStackTrace();
}
Parent fxml = FXMLLoader.load(getClass().getResource("/com/abc/fxml/LoginPage.fxml"));
pane2.getChildren().setAll(fxml);
} else {
showMessageDialog(null, "Passwords don't match!");
}
}
ps = prepared statement for SELECT query:
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
ps1 = prepared statement for INSERT statement:
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
Using the wrong prepared statement:
ps.setString(1, s12);
A suggestion - if you call the first prepared statement 'selectDepartmentDetails' and the second 'insertUserInfo', it is less likely you will run into this.

column not allowed here oracle with getText

I tried to save / edit / delete a new row in the database. writing in the gui values to be saved with getText ()
here is the code
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql;
sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (txt_isbn, txt_disp, txt_titolo, txt_casa, txt_autore, txt_genere, txt_prezzo)";
stmt = conn.createStatement();
emps = stmt.executeQuery(sql);
String ISBN= txt_isbn.getText();
String DISPONIBILITA= txt_disp.getText();
String TITOLO= txt_titolo.getText();
String CASA_EDITRICE= txt_casa.getText();
String CODICE_AUTORE= txt_autore.getText();
String GENERE= txt_genere.getText();
String PREZZO = txt_prezzo.getText();
JOptionPane.showMessageDialog(null, "SALVATO");
}catch(SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(null, e);
}
finally
{
try{
if (emps != null)
emps.close();
}
catch (SQLException e) { }
try
{
if (stmt != null)
stmt.close();
}
catch (SQLException e) { }
}
Getting this error: column not allowed here
Above code just takes care of insert operation. How can I delete and modify table record?
You have asked 2 different questions here
1. Column not allowed here
This happened because you have not passed values for any of parameter into insert statement.
I am not sure about your requirement however I will use PreparedStatement for this scenario.
Example
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "MindPeace");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement .executeUpdate();
2. This code is only to save the data, delete, and modify an entire row how can I do?
Answer is very simple. You have to write code for the same :)
You need 3 SQL statement which has DELETE and UPDATE operation just like insert in above example.
String sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, "
+ "CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.createStatement()) {
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ITALY);
String ISBN = txt_isbn.getText();
String DISPONIBILITA = txt_disp.getText();
String TITOLO = txt_titolo.getText();
String CASA_EDITRICE = txt_casa.getText();
String CODICE_AUTORE = txt_autore.getText();
String GENERE = txt_genere.getText();
BigDecimal PREZZO = new BigDecimal(
numberFormat.parse(txt_prezzo.getText()).doubleValue())
.setScale(2);
stmt.setString(1, ISBN);
stmt.setString(2, DISPONIBILITA);
stmt.setString(3, TITOLO);
stmt.setString(4, CASA_EDITRICE);
stmt.setString(5, CODICE_AUTORE);
stmt.setString(6, GENERE);
stmt.setBigDecimal(7, PREZZO);
int updateCount = stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "SALVATO");
} catch(SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
Try-with-resources closes the stmt automatically.
The prepared statement replaces the value in the SQL with something like:
INSERT INTO table(column1, colum2, ....)
VALUES('De\'l Rey',
1234.50,
...)
for:
"De'l Rey"
1.234,50
updateCount should be 1 on success.
Wooow..true!!
I created three buttons to delete / update / insert and now it all works and automatically updates the tables.
you've been very very great. Thank you very much.
one last thing.
if I wanted to insert an error message when I delete / update etc "book not found" I tried to create an if:
Boolean found = false;
try{
sql= delete......
etc
if (!found)
JOptionPane.showMessageDialog(null, "NOT FOUND","ERRORE",JOptionPane.WARNING_MESSAGE);
etc...
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql= "DELETE FROM progetto.libro WHERE isbn =?"; /
pst=(OraclePreparedStatement) conn.prepareStatement(sql);
pst.setString (1, txt_isbn.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "ELIMINATO");
Update_table();
txt_isbn.setText("");
txt_disp.setText("");
txt_titolo.setText("");
txt_casa.setText("");
txt_autore.setText("");
txt_genere.setText("");
txt_prezzo.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
if you find the book must exit the book removed, or "not found". but as I deployed I always come out "deleted". why?
thanks again

How to use dynamic table name in SELECT query using JDBC

I have 5 or table table to query from \
my syntax i like this
String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql2);
System.out.println("SQL before values are set "+sql2);
System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
// values are outputted correctly but are not getting set in the query
pst.setString(1, tblName);
pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);
while(rs2.next()){
String ID = rs2.getString("ID");
jLabel35.setText(ID);
jLabel37.setText(ID);
jLabel38.setText(ID);
// them print command is initiated to print the panel
}
The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"
When i output the sql using system.out.println(sql2);
values are not set in sql2
When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:
String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery();
String sqlStatment = "SELECT * FROM " + tableName + " WHERE Patient_ID = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sqlStatment);
preparedStatement.setint(1, patientId);
ResultSet resultSet = preparedStatement.executeQuery();
public void getByIdEmployer() throws SQLException {
Connection con = null;
try {
con = jdbcUtil.connectionDtls();
PreparedStatement ptst = con.prepareStatement(getById);
ptst.setInt(1, 4);
ResultSet res = ptst.executeQuery();
while (res.next()) {
int empid = res.getInt(1);
System.out.println(empid);
String name = res.getString(2);
System.out.println(name);
int salary = res.getInt(3);
System.out.println(salary);
String location = res.getString(4);
System.out.println(location);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.close();
}
}

compare database column values in mysql with another String in java

I have a database with the following layout
databasename:macfast
table name:users
columns
id,
user_name,
password,
fullName
I want to retrieve all the values from the column user_name and check each values with another one string which is already retrieved from a TEXTFIELD.But I can't(NullpointerException). Please help me.
public void deleteFclty() {
PreparedStatement stmt = null;
ResultSet rs = null;
String username=removeText.getText();
String qry = "SELECT user_name From users ";
try {
stmt = (PreparedStatement) connection.prepareStatement(qry);
rs = stmt.executeQuery();
while (rs.next()) {
String check=(rs.getString("user_name"));
System.out.println(check);
if(check.equals(username)){
Util.showErrorMessageDialog("EQUAL");
}else{
Util.showErrorMessageDialog("NOT EQUAL");
}
}
}catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
}
Problem is with the prepared statement (you don't put id into statement, which should be there instead of question mark).
Also I would recommend to do condition as "username.equals(check)", that can prevent null pointer exception.
"SELECT user_name From users where id=?"
This query has a parameter and you're not setting any value to it. Use PreparedStatement#setInt() or similar to set it, e.g.:
stmt.setInt(1, 1);
The problem is with PreparedStatement as you are using Question mark ? in your query for that you have to set the Id value.
String qry = "SELECT user_name From users where id=?";
stmt = (PreparedStatement) connection.prepareStatement(qry);
stmt.setInt(1,1001);
rs = stmt.executeQuery();
For your question in comment below:
List<String> values = new ArrayList();
while (rs.next()) {
values.add(0,rs.getString(<>))
}
// here do whatever you want to do...
// for example
for ( String value: values )
{
// check if value == TEXTFIELD
// if true then do something..
// else don't do anything
}

Categories

Resources