I have the following JDBC code , in which I am not getting any error, but unfortunately the data is not being added to the database. The code that I am using is :
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:../../clientDb.db");
c.setAutoCommit(false);
String expenseUUID = UUID.randomUUID().toString();
expenseUUID = expenseUUID.replaceAll("-", "");
String sqlQuery = "insert into expense (expenseUUID , user_id,expense_description,
total_amount, place, per_exp_flag, category " +
",creation_date ) values (?,?,?,?,?,?,?,?) ";
ps = c.prepareStatement(sqlQuery);
ps.setString(1, expenseUUID);
ps.setInt(2, user_id);
ps.setString(3, description);
ps.setInt(4, total_amount);
ps.setString(5, place);
ps.setInt(6, 1);
ps.setInt(7, category);
ps.setString(8, creation_date);
int result = ps.executeUpdate();
if(result == 1){
b = true;
}
What is the error ? When I tried using select statement , I got the result in the result set, But why is it not inserting anything? I am getting '1' in
int result = ps.executeUpdate();
What is possibly the error? I am using SQLite3 as back-end database.
You have c.setAutoCommit(false); so your INSERT won't actually be written to the database until you c.commit();. Add that statement after the ps.executeUpdate().
Related
I am trying register page, if email exits already it should get alert message, for this below is my some part of the code, i am using executeQuery for Select query but still i am getting error:
java.sql.SQLException: Can not issue executeUpdate() or executeLargeUpdate() for SELECTs
java code:
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/xxxx", "root","root");
PreparedStatement ps=cn.prepareStatement("select * from Register where email=?");
ps.setString(1, email);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
out.println("<script type=\"text/javascript\">");
out.println("alert('Email already Exists Please Try with New Email');");
out.println("location='index.html';");
out.println("</script>");
}
else{
PreparedStatement ps1 = cn.prepareStatement("insert into Register values(?,?,?,?,?)");
ps1.setString(1, name);
ps1.setString(2, email);
ps1.setString(3, mobile);
ps1.setString(4, password);
ps1.setString(5, conform_password);
int i = ps.executeUpdate();
if (i != 0) {
response.sendRedirect("index.html");
} else {
out.println("Some Thing went wrong. Try Again...");
}
}
}
My guess is that the problem has to do with your not closing the first statement used for the select before you try to create another statement for the insert. But, there is a better way to implement your logic, using a single insert:
String sql = "INSERT INTO Register (name, email, mobile, password, confirm_password) ";
sql += "SELECT ?, ?, ?, ?, ? ";
sql += "WHERE NOT EXISTS (SELECT 1 FROM Register WHERE email = ?)";
PreparedStatement ps = cn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, mobile);
ps.setString(4, password);
ps.setString(5, conform_password);
ps.setString(6, email);
int i = ps.executeUpdate();
if (i == 0) {
System.out.println("Email already Exists Please Try with New Email");
}
else {
response.sendRedirect("index.html");
}
If the exists clause of the above insert fails, then nothing should be inserted, and the DML row count returned by executeUpdate() should be zero.
I'm trying to check if the database has the row Comment matches according from getComments2.
If there exists such row, proceed with the next data checking else it will execute the insert statement
After I ran this code, it gave me:
java.sql.SQLException: Illegal operation on empty result set (When database is empty) or
java.sql.SQLException: After end of result set (When database is filled).
Code:
String url = "test";
String getComments2 = "test1";
String getTime1 = "test2";
String sqlSelect = "Select comment from predata";
PreparedStatement ps1 = conn.prepareStatement(sqlSelect);
ResultSet rs = ps1.executeQuery();
boolean exists = false;
while(!rs.last()||(!exists)) {
rs.next();
if(rs.getString("Comment").compareTo(getComments2)==0) {
exists = true;
}
if(!exists||rs ==null) {
PreparedStatement ps = conn.prepareStatement("INSERT into predata (topic,comment,date) VALUES (?,?,?)");
ps.setString(1, url);
ps.setString(2, getComments2);
ps.setString(3, getTime1);
ps.executeUpdate();
}
}
rs.last() moves the cursor to the last row. Then rs.next() moves it past the last row, so rs.getString("Comment") throws an exception.
The correct logic should be:
boolean exists = false;
while (rs.next() && !exists) {
if(rs.getString("Comment").equals(getComments2)) {
exists = true;
}
}
if (!exists) {
PreparedStatement ps = conn.prepareStatement("INSERT into predata (topic,comment,date) VALUES (?,?,?)");
ps.setString(1, url);
ps.setString(2, getComments2);
ps.setString(3, getTime1);
ps.executeUpdate();
}
You can use Merge in your query itself instead of checking condition in code. Else you can user Insert or Replace in query itself.
I'm trying to do an INSERT INTO SELECT which are inserting into in 1 table by selecting specific data in columns from 2 tables. The thing is, it will involve with user input from JTextField as well. I have searched for many solutions but still got an error and I just dunno what else to do. I'm using Java as PL and Oracle as DB. This is what I have got so far :
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","ghost","slayer");
stmt = con.createStatement();
String sbjC = sbjCode.getText(); //textfield for subjectCode
String sbjN = sbjName.getText(); //textfield for subjectName
String matricsno = textstudentid.getText(); //textfield for matrics number
String sbjG = sbjGrade.getText(); //textfield for subjectGrade (not gonna be use in db, just for comparison)
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = '"+sbjC+"' AND b.subjectName = '"+sbjN+"' AND s.matricsNo = '"+matricsno+"'";
/* table Transferred has 5 column which are subjectCode,subjectName,credit,prequisite,matricsNo [matricsno as FK]
* table bitm has 5 column [subjectCode as PK]
* table student has 6 column [matricsno as PK]
*/
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, "SELECT credit FROM bitm WHERE subjectCode = '"+sbjC+"' AND subjectName = '"+sbjN+"'");
ps.setString(4, "SELECT prequisite FROM bitm WHERE subjectCode = '"+sbjC+"' AND subjectName = '"+sbjN+"'");
ps.setString(5, "SELECT matricsno FROM student WHERE matricsno = '"+matricsno+"'");
ps.executeUpdate(sql1);
The only error I have got after executing and insert all data needed into JTextField is java.sql.SQLException : Invalid column index.
The SQL statement has been test in SQL Developer and succeed. Just I'm bit confused on how to do it on Java.
Thank you for all of your response and time.
I'm a newbie in Java.
For PreparedStatement, you'd code ? Into the sql and later replace that with values.
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ? ";
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3,matricsno);
ps.executeUpdate ();
This should do it.
Your error came from giving parameters (setString...) without matching ?
Unfortunately you absolutely misunderstood what the preparedStatemet does.
You have to write ? -s into the query and the preparedSatement is going to replace it on a typed way:
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ?";
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, matNo);
ps.executeUpdate();
To answer my own question, I'll put comment on the changes that I have made to the code and make it work:
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","aza","jaiza");
stmt = con.createStatement();
String sbjC = sbjCode.getText();
String sbjN = sbjName.getText();
String matricsno = textstudentid.getText();
String sbjG = sbjGrade.getText();
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ?"; // from textfield to ?
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, matricsno);
//from all the SELECT statement to just 3 user-input-from-textfield column
ps.executeUpdate(); // remove the sql1 in ps.executeUpdate(sql1);
String sql = "UPDATE `test`.`books` SET ? = ? WHERE `isbn` = ?;";
PreparedStatement ps = null;
ps = conn.prepareStatement(sql);
ps.setString(1,whatToUp);
ps.setString(2, data);
ps.setString(3, isbn);
ps.executeUpdate(sql);
System.out.println("Statement executed");
conn.close();
Error say that something is wrong with query . I am usign MySQL 5.6.
I copied the statement from the workbench 6.0 and just placed ? wherever I needed.
Even this Gives an error:
String sql = "UPDATE `test`.`books` SET `title` = ? WHERE `isbn` = ?;";
PreparedStatement ps = null;
ps = conn.prepareStatement(sql);
ps.setString(1, data);
ps.setString(2, isbn);
ps.executeUpdate(sql);
System.out.println("Statement executed");
conn.close();
You can build the query dynamically
String sql = "UPDATE `test`.`books` SET " + whatToUp + " = ? WHERE `isbn` = ?;";
PreparedStatement ps = null;
ps = conn.prepareStatement(sql);
ps.setString(1, data);
ps.setString(2, isbn);
ps.executeUpdate(); // you need to use the overloaded method without an argument
Note that you are then vulnerable to SQL injection.
If for some reason that is wrong, remove all the quotes.
String sql = "UPDATE test.books SET " + whatToUp + " = ? WHERE isbn = ?;";
If that doesn't work, then your schema doesn't match. That's up to you.
In my rush to answer I didn't see you were using
ps.executeUpdate(sql);
This method's javadoc says
Note:This method cannot be called on a PreparedStatement or
CallableStatement.
You have to use
ps.executeUpdate();
since you've already provided the sql statement to the method.
All of this would've been solved extremely quickly if you had just provided the exception stack trace. Consider that next time you ask a question
The problem is that you are calling executeUpdate(String) on a PreparedStatement, for which the documentation says:
SQLException - [...], the method is called on a PreparedStatement or CallableStatement
You need to use executeUpdate() (so without parameters) to execute a PreparedStatement. The reason is: a prepared statement already knows its query (the one it was created with), so it makes no sense to provide a query when executing it.
Note that the MySQL implementation is not entirely conforming to JDBC. It actually does allow executing with a String here, but it causes a syntax error because of the parameter placeholders.
Your first piece of code will never work, because parameters can only be used in places of values, not in places where object names (like table names) are expected.
#SotiriosDelimanolis gave you the answer.
Just build the SQL String differently
Stringbuilder sql = new Stringbuilder("UPDATE test.books SET ");
sql.append(whatToUp);
sql.append(" = ? WHERE isbn = ?");
PreparedStatement ps = null;
ps = conn.prepareStatement(sql.toString());
ps.setString(1, data);
ps.setString(2, isbn);
ps.executeUpdate(sql.toString());
System.out.println("Statement executed");
conn.close();
I have a problem with my java/jdbc code.
parameter index out of range (2 number of parameters which is 1)
Code:
Connection c = null;
MySQL MySQL = new MySQL(Host, Port, Database, Username, Password);
c = MySQL.open();
Player player = (Player) sender;
String zapytanie = "UPDATE `?` SET `tag`=? WHERE `name`='?';";
PreparedStatement ps = c.prepareStatement( zapytanie );
ps.setString(1, Tabel);
ps.setString(2, red);
ps.setString(3, player());
ps.executeUpdate(); //Executes the query
ps.close(); //Closes the query
c.close();
final String zapytanie = "UPDATE " + Table + " SET tag = ? WHERE name = ?";
No quotes around ? required
JDBC doesn't require a ; after any SQL statement
Place holders ? can only be used for column values