I am using a PreparedStatement to insert into mysql,I get no error but data has not been inserted,when I check in the mysql console it says Empty set:
public void insertGeometryValues(String gisuniqkey,String objkey,String objtype,String geometry)
{
PreparedStatement statement=null;
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values(?,?,?,?);";
try {
conn.setAutoCommit(false);
statement=(PreparedStatement) conn.prepareStatement(sql);
statement.setString(1, gisuniqkey);
statement.setString(2,geometry);
statement.setString(3,objtype);
statement.setString(4,objkey);
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I also tried using a Statement like this and get this ERROR
try {
if(conn==null)
{
System.out.println("The connection was not initialized.");
return false;
}
Statement st=(Statement) conn.createStatement();
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values('"+gisuniqkey+"','"+geometry+"','"+objtype+"',"+objkey+"');";
System.out.println(sql);
rc=st.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Your use of PreparedStatement never actually executes the statement. Change your code to:
public void insertGeometryValues(String gisuniqkey,String objkey,String objtype,String geometry) {
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values(?,?,?,?);";
conn.setAutoCommit(false);
try (PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setString(1, gisuniqkey);
statement.setString(2,geometry);
statement.setString(3,objtype);
statement.setString(4,objkey);
statement.executeUpdate(); // <---- This is what is missing!
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have also included try-with-resources so that the statement is actually correctly closed.
the answer given by Mark is correct. that should help you inserting using prepared statement.
You Sql query for inserting using Statement is incorrect. you have missed the starting ' for objkey variable. the correct query is
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values('"+gisuniqkey+"','"+geometry+"','"+objtype+"','"+objkey+"');";
Related
I have a problem with this method:
public void insertIntoQueue(DTOQueue dtoQueue) {
DbConnection dbConnection = new DbConnection();
Connection conn;
try {
conn = dbConnection.coneccion();
String sql = " INSERT INTO PURE_ENC_QUEUE (queueId,queueName) values(?,?);";
//creating PreparedStatement object to execute query
PreparedStatement preStatement = conn.prepareStatement(sql);
preStatement.setString(1, dtoQueue.getQueueId());
preStatement.setString(2, dtoQueue.getQueueName());
int result = preStatement.executeUpdate();
DbConnection.closeConnection(conn);
if(result > 0) {
System.out.println("Insertado");
} else {
System.out.println("No insertado");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("done");
}
When I run it, throws the exception
java.sql.SQLException: ORA-00933: SQL command not properly ended
Any idea about the problem? Thank you!
You need to remove the semicolon at the end of the query string, i.e.:
String sql = "INSERT INTO PURE_ENC_QUEUE (queueId,queueName) values(?,?)";
Also, it would be a good idea to refactor the code to use the try-with-resources statement.
I have a GUI JDBC SQL project. I can read the information from my Database well but i don't know what is wrong with my create,update,delete method. Seem like some methods in resultSet doesn't work correctly. My code is below.
public Person create(Person p){
try {
rs.moveToInsertRow();
rs.updateInt("PersonID", p.getPersonID());
rs.updateString("firstName", p.getFirstName());
rs.updateString("middleName", p.getMiddleName());
rs.updateString("lastName", p.getLastName());
rs.updateString("email", p.getEmail());
rs.updateString("phone",p.getPhone());
rs.insertRow();
rs.moveToCurrentRow();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return p;
}// end of create method
public Person update(Person p){
try {
rs.updateString("firstName", p.getFirstName());
rs.updateString("middleName", p.getMiddleName());
rs.updateString("lastName", p.getLastName());
rs.updateString("email", p.getEmail());
rs.updateString("phone",p.getPhone());
rs.updateRow();
rs.moveToCurrentRow();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return p;
}//end of update method
public void delete(){
try {
rs.moveToCurrentRow();
rs.deleteRow();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end of delete method
thanks for your reading.
public PersonBean() {
try {
Class.forName(JDBC_DRIVER);
Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
sm = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = sm.executeQuery("Select * From Person");
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end of PersonBean
my connection to SQL is OK because i can read information from SQL but i cant write data to SQL. Here is my error when i try to create a new Person.
com.microsoft.sqlserver.jdbc.SQLServerException: The result set is not updatable.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.throwNotUpdatable(SQLServerResultSet.java:436)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.verifyResultSetIsUpdatable(SQLServerResultSet.java:447)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.moveToInsertRow(SQLServerResultSet.java:4350)
at PersonBean.create(PersonBean.java:29)
A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. An updatable result set allows modification to data in a table through the result set. The following code makes a result set that is scrollable and insensitive to updates by others:
try {
// Create a statement that will return updatable result sets
Statement stmt = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//Primary key EmployeeID must be specified
//so that the result set is updatable
ResultSet resultSet = stmt.executeQuery(
"SELECT EmployeeID, Name, Office FROM employees");
} catch (SQLException e) {
}
You want to use following example and check this codes with your codes in project:
//database connector file example (com.mysql.jdbc.Driver)
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String DB_URL = "jdbc:mysql://localhost:3306/dbname";
String DB_USER = root;
String DB_PASS = "";
Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
Statement stmt = con.createStatement();
stmt.executeQuery("Select * From Person");
ResultSet resultSet = stmt.getResultSet();
while(resultSet .next()){
System.out.print(resultSet.getString("fieldName");
//and other your field to display
}
resultSet.close();
stmt.close()
} catch(Exceptoin e) {
....
}
There are many examples of this approach for insert, update and delete.
I'm trying to figure out how to rollback commits from multiple methods. I want to do something like the following (editing for brevity)
public void testMultipleMethodRollback() throws DatabaseException {
Connection conn = connect();
fakeMethodRollback1();
fakeMethodRollback2();
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
and currently all my methods are formatted like this
public void fakeMethodRollback1() throws DatabaseException {
Connection con = connect();
PreparedStatement ps = null;
ResultSet rs = null;
// insert some queries
try {
String query = "some query";
ps = conn.prepareStatement(query);
ps.executeUpdate(query);
query = "some query";
ps = conn.prepareStatement(query);
ps.executeUpdate(query);
con.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
throw new DatabaseException(e);
} finally {
close(rs, ps, conn);
}
}
because I want to be able to use the other methods independently, how can I do a rollback where if one method fails, the others will roll back? I fear I have my whole class setup wrong or at least wrong enough that this can't be accomplished without major work. I can't change the methods to return a connection, because half of my methods are get methods, which are already returning other data. Any ideas?
Giving error at line 12 "This method must return a result of type Boolean".
I have written my code in try catch block. If a move the resultset operation below the catch block then the error appears on resultset object.
Where am I wrong, Please answer me. Thank you.
public class LoginService {
public Boolean verifyLogin(LoginModel loginModel) { // In this line it is
// giving error
DbConnection dbConnection = new DbConnection();
ResultSet rs;
try {
Connection con = dbConnection.getConnection();
System.out.println("Connection Established");
String query = "select * from login where tenantid=? and userid=? and password=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, loginModel.getTenantid());
ps.setString(2, loginModel.getUserid());
ps.setString(3, loginModel.getPassword());
rs = ps.executeQuery();
if (rs.next()) {
System.out.println("User exists !!");
return true;
} else {
System.out.println("User does not exists !!");
return false;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
When your code catches an exception you are simply printing the stacktrace and then allowing the function to continue.
However, after the catch blocks, you have no return statement, which is what the complaint is.
As others have mentioned, you're missing a return statement either in the catch blocks or after the catch blocks. Here's my boiler plate example of a function that returns a boolean:
bool foo()
{
bool result = false;
//do stuff, and set result to true at some point
return result;
}
This pattern is beneficial because it helps reduce the number of returns in your functions. There are some coding styles out there that won't allow more than 2 return statements in a function, for example.
Here it is applied to your function:
public Boolean verifyLogin(LoginModel loginModel) { // In this line it is
// giving error
Boolean result = false;
DbConnection dbConnection = new DbConnection();
ResultSet rs;
try {
Connection con = dbConnection.getConnection();
System.out.println("Connection Established");
String query = "select * from login where tenantid=? and userid=? and password=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, loginModel.getTenantid());
ps.setString(2, loginModel.getUserid());
ps.setString(3, loginModel.getPassword());
rs = ps.executeQuery();
if (rs.next()) {
System.out.println("User exists !!");
result = true; //--------------------This line changed!
} else {
System.out.println("User does not exists !!");
result = false; //-------------------This line changed!
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
You should return in catch blocks too. Or in finally block.
You need to add a return statement after your catch block.
Your method may throw an exception, in this case, the code that will be executed will be in the catch clauses.
Add a finally clause after the catch's with the desired value for when this happens.
The problem is that if an exception occurs, nothing is returned. I would suggest adding
return false;
to all of your catch blocks
I am trying to insert question in question table and than getting that latest question id. I am trying to add options for it in other table named select_op. It inserts question successfully but not options. Even I am not getting any exception, method exits successfully.
int id=addQuestions(ques, survey_id);
if(id>0){
//not inserting anyvalue in database
String sql = "insert into select_op("+ "first,"+ "second,"+ "third,"+ "four,"+ "question_id)"+" values(?,?,?,?,?)";
try {
conn.setAutoCommit(false);
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1,option1);
pst.setString(2,option2);
pst.setString(3,option3);
pst.setString(4,option4);
pst.setInt(5,id);
pst.addBatch();
System.out.println(pst.executeBatch());
}catch (BatchUpdateException e) {
try {
System.out.println(e);
conn.rollback();
} catch (Exception e2) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//this function insert data successfully
public int addQuestions(String ques,String survey_id){
String sql = "insert into question(question,survey_id) values(?,?)";
int id = 0;
try {
conn.setAutoCommit(false);
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1,ques);
pstmt.setString(2,survey_id);
pstmt.addBatch();
pstmt.executeBatch();
ResultSet keys = pstmt.getGeneratedKeys();
keys.next();
id = keys.getInt(1);
keys.close();
conn.commit();
pstmt.close();
}
catch (BatchUpdateException e) {
try {
conn.rollback();
} catch (Exception e2) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return id;
}
Any Suggestion?
As Zaki Suggested
Are you missing a commit ?
I did commit.. Solved :)
Thanks
getGeneratedKeys() may not be supported in mysql (I've never seen it used or tried it).
But I do know this works: Executing the query select mysql_insert_id() returns the last auto increment value - use that instead of getGeneratedKeys().