I always get this error every time i try to save or execute the query.
I can't work it out,maybe alittle advice will help.
java.sql.SQLException: can not issue data manipulation statements with
executeQuery()
here is my code for inserting into my database.
Connection conn=null; ResultSet rs = null,rs1=null; PreparedStatement
pst = null,pst1=null;
DefaultTableModel model= (DefaultTableModel)tbl_stud.getModel();
try{
String sql="INSERT INTO students (id_num,fname,mname,lname,course,gender,year,username,password) VALUES(?,?,?,?,?,?,?,?,?);";
model.setNumRows(0);
pst=conn.prepareStatement(sql);
String id=txt_idnum.getText();
pst.setString(1,id);
String f=txt_fname.getText();
pst.setString(2, f);
String m=txt_mname.getText();
pst.setString(3, m);
String l=txt_lname.getText();
pst.setString(4, l);
String crs=cmb_course.getSelectedItem().toString();
pst.setString(5, crs);
String gen=cmb_gender.getSelectedItem().toString();
pst.setString(6, gen);
String year = cmb_year.getSelectedItem().toString();
pst.setString(7, year);
String uname=txt_username.getText();
pst.setString(8, uname);
String pass=txt_password.getText();
pst.setString(9, pass);
pst.executeQuery(sql);
JOptionPane.showMessageDialog(null, "Saved!","",JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e,"",JOptionPane.ERROR_MESSAGE);
}
you need to use pst.executeUpdate rather then pst.executeQuery
The exception message says it all:
can not issue data manipulation statements with executeQuery()
Instead, you should use executeUpdate(). Additionally, if you've already prepared the statement, you should use the execute variants that do not receive a String argument. Those are inherited from Statement and should not be used with PreparedStatements (and yes, this does go a long way towards showing that JDBC is a terrible API).
pst.executeUpdate();
As an additional sidenote, you should drop the semicolon (;) and the end of your insert statement. Depending on the exact driver and RDBMS you're using it may either be redundant or just plain out wrong.
Related
Well the main problem here is, the detection of the duplicate entries in the Jtable, the Detection of duplicate entries will work when your enter the SAME/IDENTICAL data for the third time. It would not work in the second time and duplicate.
how can i add a unique constrain in my mysql? i dont know how to do it. Please let me have a specific instructions on how to execute it
2nd try (duplicate)
3rd try(the detection works)
database
JAVA NETBEANS
DATABASE: MYSQL
I think the problem would be the try-catch part which is the part that I dont understand. Thank You in Advance.
Heres my codes:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String first = firstname.getText();
String last = lastname.getText();
String gen = gender.getText();
String strand = cboStrand.getSelectedItem().toString();
String aged = age.getText();
String add = address.getText();
try{
String sql;
sql = "INSERT INTO idusjavanew"
+ "(fname,lname,sex,strand,age,address)"
+ "VALUES (?,?,?,?,?,?)";
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/idusjavanew?zeroDateTimeBehavior=convertToNull","root","");
pst = con.prepareStatement(sql);
pst.setString(1, firstname.getText());
pst.setString(2, lastname.getText());
pst.setString(3, gender.getText());
pst.setString(4, cboStrand.getSelectedItem().toString());
pst.setString(5, age.getText());
pst.setString(6, address.getText());
String selectQuery;
selectQuery = "select * from idusjavanew where fname ='"+first+"' and lname='"+last+"'";
System.out.println(selectQuery);
rs = pst.executeQuery(selectQuery);
System.out.println(rs.next());
if (rs.next()==false){
pst.executeUpdate();
JOptionPane.showMessageDialog(null , "Information has been recorded!");
showTableData();
}
else{
JOptionPane.showMessageDialog(null,"Information already added!");
showTableData();
}
}
catch(HeadlessException | SQLException ex)
{
JOptionPane.showMessageDialog(null,ex);
}
showTableData();
}
You are calling next() twice on your result set once in print statement and once in if, that is causing the issue.
So according to your current code if you already have an entry the 1st call to next() will point it to that entry and the second call will return false. That is why it detects duplicate on third row entry.
So just remove System.out.println(rs.next()); and your code should work as intended.
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,"+u+","+p+",'1')");
I'm getting the error
java.sql.SQLException: Unknown column '(the U variable)' in 'field list';
I know for sure it is 100% the "" but i can't seem to find it where it goes wrong
any help is appreciated!
This is my whole method (I want to learn how to do it with a prepared statement)
public static void connectionDB(String u, String p, String f){
{
try {
String username = "/////////";
String password = "///////";
String url = "///////////////";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Database connected!");
}
}
It should be like
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");
Update:-
You can also look into prepared statements because
Prepared statements are much faster when you have to run the same statement multiple times, with different data. Thats because SQL will validate the query only once, whereas if you just use a statement it will validate the query each time.
Assuming fields are A,B,C,D;
A is int and remains are strings
String insertTableSQL = "INSERT INTO Leden"
+ "(A,B,C,D) VALUES"
+ "(?,?,?,?)";
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "Hello");
preparedStatement.setString(3, "this");
preparedStatement.setString(4, "OP");]
preparedStatement .executeUpdate();
It should be
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')'");
The issue is, that " is used in SQL for objects like columns or tables, whereas ' is used for strings. So in +u+, which seems to not exists in context of your query.
Your query itself should therefore look something like (given, that +u+ and +p+ are strings.
INSERT INTO Leden VALUES (null,'+u+','+p+','1')
If you need to have " inside your columns, it would read like
INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')
Also I would recommend to specify the columns you are inserting to so it looks similar to:
INSERT INTO "Leden" ("col1", "col2", "col3", "col4") VALUES (null,'+u+','+p+','1')
This will prevent your query from failing when extending table definition by another column.
Also using prepared statements could be a good idea here, as it helps you preventing from e.g. SQL injections.
I was updating password in an oracle databse using a java servlet like this
Connection con;
PreparedStatement ps,ps1;
ResultSet rs;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (ClassNotFoundException e)
{
System.out.println("Drivers Not Found");
}
try{
con=DriverManager.getConnection("jdbc:odbc:SharedCryptography", "fyp", "fyp");
}catch(SQLException e1)
{
}
String query="UPDATE tbGroup SET GPassword='"+mypassword+"' where GName='"+GroupNamee+"' and OEmail='"+OwnerId+"'";
java.sql.Statement stmt = con.createStatement();
stmt.executeUpdate(query);
But it gives java.sql.SQLException: [Oracle][ODBC][Ora]ORA-01756: quoted string not properly terminated
Am i doing something wrong in it?Please help
You should absolutely avoid string concatenation in SQL statements. You will get in all kind of security and stability problems. Your problem is simply be resolved by using a prepared statement:
String sql="UPDATE tbGroup SET GPassword=? where GName=? and OEmail=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, myPassword);
ps.setString(2, groupName);
ps.setString(3, ownerId);
ps.executeUpdate();
If you do this, no "'" or "%" or "_" or " in your parameters will cause any problems. Alternatively you can try to escape your characters, but why bother - the PS method is not only more robust and easier to read, it is often also more performant.
For a general description of the security problems, see: https://www.owasp.org/index.php/SQL_injection
One of your variables (probably password) has a quote or semi colon in it. Since you build up your query via String concatenation, you are vulnerable to SQL injection attacks. It looks like you accidentally attacked yourself via injection. If you had a properly maliciously formatted variables you could have done quite a bit of damage to your database.
Please use Parameterized queries
PreparedStatement stmt = con.prepareStatement("UPDATE tbGroup SET GPassword= ? where GName= ? and OEmail=?" )
stmt.setString(1, mypassword);
...
stmt.executeUpdate();
See this for more details
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
hello everyone i need your help.. i'm trying to save data to mysql database in java using netbeans IDE my source code doesn't want to run"it gives me an error that says"Java.lang.NullPointerExcepion
here's my source code..
try{
String sql = "Insert into clients(username,Id_number,surname,fullname,age,diagnose) values(?,?,?,?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, txt_surname.getText());
pst.setString(2, txt_fullname.getText());
pst.setString(3, txt_age.getText());
pst.setString(4, txt_diagnose.getText());
pst.setString(5, txt_ID.getText());
pst.setString(6, txtusername.getText());
//pst.setString(7, txt_password.getText());
pst.execute();
JOptionPane.showMessageDialog(null,"Saved");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
This code is clear and ok. the only possible var causing trouble is con. So try to add a sysout print statement before all con == null and look if it is true, then check whats missing on the connection setup
this is my edited code...
java.sql.Timestamp sqlNow = new java.sql.Timestamp(new java.util.Date().getTime());
stmt = con.createStatement();
//stmt.executeUpdate("INSERT INTO cregn values('"+appno+"','"+usname+"','"+upwd +"','"+fname+"','"+mname+"','"+lname+"','"+dob+"','"+gend+"','"+faname+"','"+saddr+"','"+caddr+"','"+staddr +"','"+pin+"','"+cno+"','"+email+"','"+occ+"','"+secques+"','"+answer+"','Processing','"+sqlNow+"')");
pst = con.prepareStatement("INSERT INTO cregn (aplno, username, pwd, firstname,middlename,lastname, dob,gender, fathername, street,city,state, pincode, phone, email,occupation,secques,answer,dor) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pst.setInt(1, appno);
pst.setString(2, usname);
pst.setString(3, upwd);
pst.setString(4, fname);
pst.setString(5, mname);
pst.setString(6, lname);
pst.setString(7, dob);
pst.setString(8, gend);
pst.setString(9, faname);
pst.setString(10, saddr);
pst.setString(11, caddr);
pst.setString(12, staddr);
pst.setString(13, pin);
pst.setString(14, cno);
pst.setString(15, email);
pst.setString(16, occ);
// pst.setString(17,ph);
pst.setString(17, secques);
pst.setString(18, answer);
pst.setTimestamp(19, sqlNow);
pst.executeUpdate();
out.println("Registration Successful for application " + appno);
} catch (Exception ee) {
out.println("Invalid Data! All fields are mandatory..." + ee.getMessage());
}
%>
after executing this code error displayed "Invalid Data! All fields are mandatory..data truncation"
You are not executing the statement.
You need to call executeUpdate
You have to call execute or executeUpdate on pst in order to actually do the work. E.g., at the end:
pst.executeUpdate();
All that the code you've shown does is prepare the statement for execution, it doesn't execute it. This is one of the main differences between PreparedStatement and Statement. In Statement, you pass the SQL to execute directly into executeUpdate (as seen in your commented-out line using stmt). With a PreparedStatement, you supply the SQL with ? as you've done, set those parameters, and then call executeUpdate (or execute), which you haven't done.
There is no executeUpdate() being called on pst.
use pst.executeUpdate(); to execute the query and make sure that in transaction use setAutoCommit(true) has to be called.