I'm trying to add Insertquery in a database. everything is working fine and I'm not getting any error. But data which I inserted in a database is not reflected on a database. In sort, Database is not updated.
try{
Database_Operation db = new Database_Operation();
db.connection();
db.cn.setAutoCommit(false);
db.cn.commit();
PreparedStatement ps1=db.cn.prepareStatement("insert into product values(?,?,?)");
Boolean status = true;
ps1.setString(1,name.getText());
ps1.setString(2, price.getText());
ps1.setString(3, status.toString());
db.cn.close();
JOptionPane.showMessageDialog(this," Data saved ", "succsess" ,1);
}catch(Exception e){
e.printStackTrace();
}
What is wrong here?
Your execution statement is si missing.
You're just forming the query and not executing it.
Before closing your db connection, add this line to your code:
ps1.executeUpdate;
You are missing the execution statement. Add following line before DB close.
ps1.executeUpdate();
You must have an execution method in Database_Operation and execute then just after the initialisation of the prepareStatement like this:
try {
// execute update SQL stetement
ps1.executeUpdate();
System.out.println("Record is updated to DBUSER table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
you haven't execute the PreparedStatement.Add the below line ps1.execute();
try{
Database_Operation db = new Database_Operation();
db.connection();
db.cn.setAutoCommit(false);
db.cn.commit();
PreparedStatement ps1=db.cn.prepareStatement("insert into product values(?,?,?)");
Boolean status = true;
ps1.setString(1,name.getText());
ps1.setString(2, price.getText());
ps1.setString(3, status.toString());
ps1.execute();
db.cn.close();
JOptionPane.showMessageDialog(this," Data saved ", "succsess" ,1);
}catch(Exception e){
e.printStackTrace();
}
Related
I am developing an app that retrieve data from SQL Server.
I have to execute 2 queries together to come out with result. The problem is the first query is a Stored Procedure that contain (INSERT INTO... EXEC sp_....), this query is shows error in server side but it is executed well, then the second query will read from the inserted result into it sue the first query.
The problem is, when the fist query execute, it make the App goes to Exception part which do not allow the second query to be executed.
Is there any way to make Android Studio ignore the error and execute the second query?
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
message = "Error in connection with SQL server";
} else {
String query = "EXEC [dbo].[sp_ReminderTimeToArriveTheBus]" +
" '"+str_wilayat+"','"+str_city+"', '"+str_station+"', '"+str_distnation+"', '"+currentTime+"'";
PreparedStatement stmt = con.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
rs.next();
String query2 = "SELECT OutputValue FROM [dbo].[FinalResultTable]";
PreparedStatement stmt2 = con.prepareStatement(query2);
ResultSet rs2 = stmt2.executeQuery();
str_min = rs2.getString("OutputValue");
if(rs2.next())
{
message = "O.K.";
str_min = rs2.getString("OutputValue");
isSuccess=true;
}
else{
isSuccess=false;
}
stmt.close();
rs.close();
stmt2.close();
rs2.close();
}
}
catch (Exception ex)
{
message = "Error";
}
return message;
}
If i am understanding the question correctly is query2 should be executed in every situation. You can try running this query in place of "Return message"after catch clause.
I solve the issue through re-write the first query (the stored procedure) and it is executing without errors now.
:)
I am working on Java Application and trying so hard to update record in SQLite database but it doesn't work .. btw it doesn't give me any exceptions or errors
String sql="update Food_Fresh set available=? where Type_ID =?";
st=con.prepareStatement(sql);
st.setInt(1, 1);
st.setInt(2, num);
st.executeUpdate();
st.close();
What's the problem ?!
UPDATE
yes , the initialization of sql
try{
Class.forName("org.sqlite.JDBC");
Connection con=DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Shatha2012\\Desktop\\Core\\IT\\Graduation Project\\Code\\New folder\\Food\\src\\Food\\Food.sqlite");
JOptionPane.showMessageDialog(null, "DONE");
return con;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
and the committing is set as auto commit
Maybe there are no records in your database with Type_ID = num?
Check the value returned from executeUpdate()
int i = st.executeUpdate();
it will show you the number of records updated
I have a stored procedure in Oracle Database like this:
CREATE OR REPLACE PROCEDURE PSTATISTIC
AS
BEGIN
UPDATE PLACE_STATISTIC
SET POPULARITY = 0;
UPDATE PLACE_STATISTIC
SET POPULARITY = POPULARITY + 1
WHERE PLACE_ID IN (SELECT PLACE_COMMENT.PLACE_ID
FROM PLACE_COMMENT);
END PSTATISTIC;
When I called it on SQL Developer:
EXECUTE PSTATISTIC
It executed normally, the PLACE_STATISTIC table was updated
But when I tried to use it on Java:
String sql="EXECUTE HR.PSTATISTIC";
Statement statement=(Statement)connectionDB.createStatement();
statement.execute(sql);
It didn't work out on Java, citing sort of errors:
java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:439)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:395)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:802)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:436)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:186)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:521)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:194)
at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:1000)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1307)
at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1882)
at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1847)
at oracle.jdbc.driver.OracleStatementWrapper.execute(OracleStatementWrapper.java:301)
How can I execute my PSTATISTIC procedure on Java? I granted all necessary privileges
To execute a stored procedure from Java code, you need to use CallableStatement. Statement cant be used to execute Stored Proc.
Connection con = getConnection();
CallableStatement cs = null;
try {
cs = con.prepareCall("{call EXECUTE PSTATISTIC}");
cs.execute();
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
}
finally {
if (cs != null) {
try {
cs.close();
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
}
}
}
}
You need to use CallableStatement for executing your Stored procedure
String procName= "{call PSTATISTIC}";
CallableStatement cs = conn.prepareCall(procName);
cs.executeQuery();
here is my very simple table (Postgres):
CREATE TABLE IF NOT EXISTS PERFORMANCE.TEST
(
test text NOT NULL UNIQUE
);
if I try to insert a String using the command below FROM the database,everything works as expected, not surprisingly a new row appears in the DB.
insert into performance.test (test) values ('abbbbaw');
However if I want to insert a String through JDBC, nothing gets inserted, although preparedStatement.executeUpdate() always returns 1.
Below is my method that should be working but it does not. Please tell me if I am missing something obvious.
I want to add that I never get any SQLException.
private void storePerformance() {
Connection conn= initializePerformanceConnection();
if (conn!= null) {
PreparedStatement insertPS = null;
try {
insertPS = conn.prepareStatement("insert into performance.test (test) values (?)");
insertPS.setString(1, queryVar);
int i = insertPS.executeUpdate();
LogManager.doLog(LOG, LOGLEVEL.INFO," numberofrows= "+i);
} catch (SQLException e) {
LogManager.doLog(LOG, LOGLEVEL.INFO,"Inserting query failed = "+queryVar,e);
}finally{
if(insertPS != null){
try {
insertPS.close();
} catch (SQLException e) {
LogManager.doLog(LOG, LOGLEVEL.INFO,"Closing PreparedStatement failed = "+queryVar,e);
}
}
try {
conn.close();
} catch (SQLException e) {
LogManager.doLog(LOG, LOGLEVEL.INFO,"Closing performanceConnection failed= "+ queryVar, e);
}
}
}
}
that was missing:
conn.commit();
(after the executeUpdate())
actually a new row was inserted but the DB rolled back immediately.
executeupdate is for a 'update table set column = value so on'. For insert just call execute of PreparedStatement.
I want to update data from my database using java. I have established my connection successfully and When I am updating the table,the data is not updated in the database.
My SQL is like this ::
UPDATE tbl_Bus SET Bus_locX= 520.0,Bus_locY=220.0 WHERE Bus_ID=1
This statement does not update my table though it's working fine when I am using it directly in sql editor in MS Access.
My tbl_Bus
Bus_ID,Bus_LocX,Bus_LocY,Bus_RouteID
and the corresponding data are 1,1,1,1 even after running my app..
My codes
public boolean update_busLoc(double x,double y,int id)
{
String query="UPDATE tbl_Bus SET Bus_locX= "+ x +",Bus_locY="+y + " WHERE Bus_ID="+id;
System .out.println(query);
if (DB_connection!=null){
try{
statement.execute(query);
return true;
}
catch(SQLException e){
e.printStackTrace();
return false;
}
}
else{
System.out.println("Connection is not set up");
return false;
}
}
I use MS Access 2007
I am able to execute SELECT statements and it is working fine but with update I am having problems..
How do I sort this out?
replace
stmt.execute(query);
with
stmt.executeUpdate(query);
Use executeUpdate instead of execute
Is your connection set to autocommit? This might be the problem
I hope this is help full
Replace execute with executeUpdate
use preparedStatement instead of statement
PreparedStatement pstmt = con.prepareStatement("UPDATE tbl_Bus SET Bus_locX=?,Bus_locY=? WHERE Bus_ID=?");
pstmt.setDouble(1, x);
pstmt.setString(2, y);
pstmt.setInt(3, id);
if (DB_connection!=null){
try{
pstmt.executeUpdate();
return true;
}
catch(SQLException e){
e.printStackTrace();
return false;
}
}
else{
System.out.println("Connection is not set up");
return false;
}