I have problem with my Programs . Help me please.
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
Class.forName("com.mysql.jdbc.Driver");
String path = "jdbc:mysql://localhost:3306/sampledb";
String Username = "root";
String Password = "";
Connection con = DriverManager.getConnection(path, Username, Password);
Statement s = con.createStatement();
String rGanTz = "UPDATE info SET Firstname = '"+txt_Firstname.getText()+"', Lastname = '"+txt_Lastname.getText()+"', Contact = '"+txt_Contact.getText()+"', WHERE '"+txt_Edpno.getText()+"'=EDPNO";
s.executeQuery(rGanTz);
JOptionPane.showMessageDialog(null,"Data has been successfully Updated","Update file", JOptionPane.INFORMATION_MESSAGE,null);
You should really consider what #OllieJones says in the comments about using prepared statements. #Rimas already gave you the solution so I will simply provide an example:
Connection con = DriverManager.getConnection(path, Username, Password);
String rGanTz = "UPDATE info SET Firstname = ?, Lastname = ?, Contact = ? " +
"WHERE EDPNO = ?";
PreparedStatement ps = con.prepareStatement(rGanTz);
ps.setString(1, txt_Firstname.getText());
ps.setString(2, txt_Lastname.getText());
ps.setString(3, txt_Contact.getText());
ps.setString(4, txt_Edpno.getText());
ps.executeUpdate();
Related
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.
I need to write a query to update a row in the database. but exception is
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Erreur de syntaxe pr?s de 'SET eMail = '11111', SET phoneNumber = '111111' WHERE name = 'Saba', surname= 'M' ? la ligne 1 .
what is the problem?
public static void updateUser(User user, Connection connection) throws SQLException {
PreparedStatement ps = null;
ps = connection.prepareStatement("UPDATE USERS SET login = ?, SET eMail = ?, SET phoneNumber = ? WHERE name = ?, surname= ?");
ps.setString(1, user.getLogin());
ps.setString(2, user.geteMail());
ps.setString(3, user.getPhoneNumber());
ps.setString(4, user.getName());
ps.setString(5, user.getSurname());
ps.executeUpdate();
The UPDATE statement only has a single SET clause. You repeated the SET keyword, which is wrong. Besides, you forgot the AND keyword to combine predicates. Write this instead:
try (PreparedStatement ps = connection.prepareStatement(
"UPDATE USERS "
+ "SET login = ?, eMail = ?, phoneNumber = ? "
+ "WHERE name = ? AND surname = ?")) {
// ...
}
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();
}
I am building a simple security system using java (eclipse) and I am using the MYSQL statement to pull data from the database
ResultSet rs = statement.executeQuery("select name, username, password from securitysystem.employee where username = '" + username + "' and password = '" + password + "'");
but what if i wanted to create a variable user= name, how would I do that? name is referring to the name retrieved using the statement above.
Firstly, you should never put your parameter right into a query string.
Instead, do this:
PreparedStatement ps = connection.prepareStatement("select name, username, password "+
"from securitysystem.employee where username = ? and password = ?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
To get the results, do this:
if (rs.next()) { //move to 1st result row
String name = rs.getString(1); //first result column
String user = rs.getString(2); //second result column
// ..etc
}
How about:
while(rs.next()) {
String user = rs.getString("name");
}
i want to use getParameter to get in Strings and ints and put them in a database using prepareStatement and SQL. It gives me errors with setString and setInt.
try {
String id = request.getParameter("clientid");
String cname = request.getParameter("clientname");
String address = request.getParameter("address");
String phonemodel= request.getParameter("phonemodel");
String imei = request.getParameter("imei");
String problem = request.getParameter("problem");
String date2 = request.getParameter("date");
String comments1= request.getParameter("comments");
int clientid = Integer.parseInt(id);
int imeino = Integer.parseInt(imei);
// int date1 = Integer.parseInt(date2);
Statement pstmt;
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app" , "app");
pstmt=con.prepareStatement("Insert into movilapp(id,clientname,address,modle,imei,problem,date,comments) values(?,?,?,?,?,?,?,?)");
pstmt.setInt(1,clientid);
pstmt.setString(2,cname );
pstmt.setString(3,address);
pstmt.setString(4,phonemodel);
pstmt.setInt(5,imeino);
pstmt.setString(6,problem);
pstmt.setString(7, comments1);
pstmt.executeUpdate();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
You called con.prepareStatement to get a PreparedStatement, but then you assigned it to a variable of type Statement, so Java doesn't know that there is a PreparedStatement-specific method setString.
Assign it to an actual PreparedStatement variable, by changing the declaration type of pstmt from
Statement pstmt;
to
PreparedStatement pstmt;
*IF Use Statement Then its syntax is *
Statement stmt = null;
stmt = conn.createStatement( );
String sql = "UPDATE Employees set age=30 WHERE id=103";
stmt.executeUpdate(sql);
And for PreparedStatement it is
PreparedStatement pstmt = null;
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
psmt.setInt(1,30);
psmt.setInt(2,1003);
psmt.executeUpdate(SQL);
So change Statement pstmt; to PreparedStatement pstmt = null; And it will work.