Here is the code
import java.sql.*;
public class Insertdb {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con= DriverManager.getConnection("jdbc:odbc:Dsn1");
PreparedStatement ps= con.prepareStatement("insert into Table1 values (?,?,?)");
ps.setInt(1,1);
ps.setString(2,"Sachin");
ps.setInt(3,25000);
int i=ps.executeUpdate();
if(i>0)
{
System.out.println(i +"records inserted");
}
}
catch(Exception e)
{
System.out.println(e);
}
// TODO code application logic here
}
}
The data base used is MS Access 2013.
The output of the above code on the console is: 1 records inserted
But when i open the database the record is not inserted. Is there any thing wrong in the code? If not what could be going wrong?
also add at the end.
finally{
con.commit();
ps.close();
con.close();
}
Any Transaction from program to database must be committed to get reflected in JAVA.
Try doing con.commit();
Try to use finally in your code if you are connecting with database or perform file operations.Because whatever happened on try block the finally block always executed.so you can use finally block for closing the database connection and close the file and commit or rollback the database records.
Related
I am trying to create a new database file named test in the folder D:\sqlite, using JDBC, as follows:
import java.sql.*;
public class Class1 {
private static void createNewDataBase(){
String url = "jdbc:sqlite:D:sqlite/";
Connection conn = null;
Statement statement = null;
try{
conn = DriverManager.getConnection(url);
System.out.println("Connection Established");
statement = conn.createStatement();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
try {
statement.execute("CREATE DATABASE test");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally{
try{
if(statement != null)
statement.close();
}catch(SQLException e){
System.out.println(e.getMessage());
}
try{
if(conn != null)
conn.close();
}catch(SQLException e){
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args){
createNewDataBase();
}
}
When I run the project, I get the following output:
Connection Established
[SQLITE_ERROR] SQL error or missing database (near "DATABASE": syntax error)
Process finished with exit code 0
It says the syntax is wrong but I can't find the error. I've looked for answers for similar questions, but none solved my problem. Can anyone tell me what's the problem? Thanks in advance!
As already stated by #Andreas, there is no CREATE DATABASE SQL statement for SQLite. To create a new SQLite database you need to merely make a connection to one and it is automatically created (you do however need to ensure that the D:/sqlite/ path already exists within the local file system).
The following code should create an empty (no tables) SQLite Database named MyNewDatabase.sqlite within the folder sqlite located in the root of drive D of your local file system:
String dbPath = "D:/sqlite/MyNewDatabase.sqlite";
Connection conn = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + dbPath;);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
catch (SQLException ex) {
ex.printStackTrace();
}
finally {
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) { e.printStackTrace(); }
}
Now you need to create one or more Tables for your new database to make it useful. SQLite does accept the CREATE TABLE SQL statement and you could do this through the same connection if desired.
The database exists, it has been connected i.e the database is the connection, which is basically the file. Hence there is no SQL for CREATE DATABASE.
Inside the database you would typically create tables (and perhaps other components).
e.g. CREATE TABLE mytable (mycolumn TEXT, myothercolumn INTEGER) which would create a table named mytable with 2 columns mycolumn and myothercolumn (the former being defined with a column type of TEXT, the latter with a column type of INTEGER).
As such, if you were to change :-
statement.execute("CREATE DATABASE test");
to :-
statement.execute("CREATE TABLE mytable (mycolumn TEXT, myothercolumn INTEGER)");
Note you'd only want to do this once, otherwise it would fail as the table already exists, so you could use CREATE TABLE IF NOT EXISTS mytable (mycolumn TEXT, myothercolumn INTEGER), of cousre it depends upon your requirements.
You may find that it will work. Obviously you will need to do other things such as add some data as the table will be empty.
Perhaps then try
statement.execute("INSERT INTO mytable VALUES('fred',100)");
Every time this is run a new ROW will be added to the table name mytable.
this my code to execute update query
public boolean executeQuery(Connection con,String query) throws SQLException
{
boolean flag=false;
try
{
Statement st = con.createStatement();
flag=st.execute(query);
st.close();
st=null;
flag=true;
}
catch (Exception e)
{
flag=false;
e.printStackTrace();
throw new SQLException(" UNABLE TO FETCH INSERT");
}
return flag;
}
maximum open cursor is set to 4000
code is executing
update tableA set colA ='x',lst_upd_date = trunc(sysdate) where trunc(date) = to_date('"+date+"','dd-mm-yyyy')
update query for around 8000 times
but after around 2000 days its throwing exception as "maximum open cursors exceeded"
please suggest code changes for this.
#TimBiegeleisen here is the code get connecttion
public Connection getConnection(String sessId)
{
Connection connection=null;
setLastAccessed(System.currentTimeMillis());
connection=(Connection)sessionCon.get(sessId);
try
{
if(connection==null || connection.isClosed() )
{
if ( ds == null )
{
InitialContext ic = new InitialContext();
ds = (DataSource) ic.lookup("java:comp/env/iislDB");
}
connection=ds.getConnection();
sessionCon.put(sessId, connection);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return connection;
}
`
error stack is as bellow
java.sql.SQLException: ORA-01000: maximum open cursors exceeded
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208)
at oracle.jdbc.ttc7.Oopen.receive(Oopen.java:118)
at oracle.jdbc.ttc7.TTC7Protocol.open(TTC7Protocol.java:472)
at oracle.jdbc.driver.OracleStatement.<init>(OracleStatement.java:499)
at oracle.jdbc.driver.OracleConnection.privateCreateStatement(OracleConnection.java:683)
at oracle.jdbc.driver.OracleConnection.createStatement(OracleConnection.java:560)
at org.apache.tomcat.dbcp.dbcp.DelegatingConnection.createStatement(DelegatingConnection.java:257)
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.createStatement(PoolingDataSource.java:216)
at com.iisl.business.adminbo.computeindex.MoviIndexComputeBO.calculateMoviValue(MoviIndexComputeBO.java:230)
Your code has a cursor leak. That's what is causing the error. It seems unlikely that your code can really go 2000 days (about 5.5 years) before encountering the error. If that was the case, I'd wager that you'd be more than happy to restart a server twice a decade.
In your try block, you create a Statement. If an exception is thrown between the time that the statement is created and the time that st.close() is called, your code will leave the statement open and you will have leaked a cursor. Once a session has leaked 4000 cursors, you'll get the error. Increasing max_open_cursors will merely delay when the error occurs, it won't fix the underlying problem.
The underlying problem is that your try/ catch block needs a finally that closes the Statement if it was left open by the try. For this to work, you'd need to declare st outside of the try
finally {
if (st != null) {
st.close();
}
}
As mentioned in another response you will leak cursors if an exception is thrown during the statement execution because st.close() won't be executed. You can use Java's try-with-resources syntax to be sure that your statement object is closed:
try (Statement st = con.createStatement())
{
flag=st.execute(query);
flag=true;
}
catch (Exception e)
{
flag=false;
e.printStackTrace();
throw new SQLException(" UNABLE TO FETCH INSERT");
}
return flag;
One of quickest solution is to increase cursor that each connection can handle by issuing following command on SQL prompt:
alter system set open_cursors = 1000
Also, add finally block in your code and close the connection to help closing cursors when ever exception occurs.
Also, run this query to see where actually cursor are opened.
select sid ,sql_text, count(*) as "OPEN CURSORS", USER_NAME from v$open_cursor
finally {
if (connection!=null) {
connection.close();
}
I just started with sqlite and I stuck with a strange (maybe just for me) phenomenon. When I connect the testDB.db file in java, and make one or some query, the data and the table itself is disappearing. The consol said that SQL error or missing database, and when I check the database file in cmd, the situation is really that; there is no data in the file. Could anybody help me out with this basic problem? (I suppose that this is just because of the lack of my knowledge in this topic, but I'm open to new information)
public class jdbcTest{
public static void main(String[] strg) {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Username\\Documents\\sqlite\\testDB");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30);
//statement.executeUpdate("drop table if exists person");
ResultSet rs = statement.executeQuery("select * from company");
while (rs.next()){
System.out.print("id = "+rs.getInt("id")+" ");
System.out.println("name = "+rs.getString("name"));
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
finally {
try {
if (connection!=null){
connection.close();
}
}
catch (SQLException e){
System.err.println(e);
}
}
}
}
When opening a nonexistent database file, SQLite will happily create a new, empty one.
The file name you're giving to getConnection does not actually point to the database you saved.
Is there any other way to properly close the connection to ms access database at the end of the infinite loop? Because if a record is inserted into the table, with my code below I can't see the new row/rows inserted. It looks like that the database is not closing corectly or something...no idea why it is acting like this. If I manually close or open the database (with my program still running in the background) everything is ok - the new row/rows will appear in my query.
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws RemoteException,
InterruptedException, SQLException {
while (true) {
Connection con = DBConnection.getDBConnection();
System.out.println("Connection OK!");
Statement s = null;
try {
ResultSet rs = null;
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
con.setAutoCommit(true);
rs = s.executeQuery("SELECT Tel, Msg, Procesat FROM RcvMsg WHERE Procesat = 'NOK'");
while (rs.next())
{
String pn = rs.getString(1);
String str = rs.getString(2);
//do something
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
s.close();
con.close();
}
Thread.sleep(5000);
}
}
}
The code you're showing is correct, but totally irrelevant for you problem because you are just reading. How do you insert the records? Manually with Access, so using another process(different from the java process) ? In this case, ucanaccess will be able to read those new data when they are phisically stored on the access file (and it may happen at the closure of a table in access and always when you close the database).
Also, if you inserted the data with another thread(different from that one in polling), you would see all records inserted (without any apparent delay problem).
If you set AutoCommit to false (thus disabling automatically committing) you should call Connection.commit() manually, otherwise nothing will ever end up permanently in the database.
You are setting Auto Commit false. Set it to true. Then your changes will reflect permanently or by default, new connections are in auto-commit mode so you can remove that line.
try to close all the open tables and queries in the MSAccess client and click on "Refresh All" and then check if the data is reflecting
//in context listener
Statement stmt;
try {
Class.forName("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:orcl","abc", "abc");
stmt = conn.createStatement();
sce.getServletContext().setAttribute("stmt", stmt);
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
}
//in Servlet page
try {
Statement stmts=(Statement) getServletContext().getAttribute("stmt");
stmts.executeUpdate("INSERT INTO COMPANYS values(1,'ahmed',5,'t012','t345','email#eamil','adressadress')");
System.out.println("connection succeed");
} catch (SQLException e) {
System.out.println("connection fail");
}
in Servlet page "try code" is execute and "connection succeed" is appearing but in oracle database there is no data inserted >> why???
use con.setAutoCommit(false); after conn has created. Once the transaction completes i.e.,after executeUpdate(...) call con.commit(); It will solve your issue if their are no errors displayed on the console.
Try it again with below steps
Set auto commit as false
Commit after updating the record to make it persisted in the database
Rollback if there is any exception while inserting the record
Don't forget to clean-up the environment such as ResultSet, Statement etc.
Code in finally block to close the resources
Don't keep connection opened for long time.
Must read
Is it mandatory to close all ResultSets, Statements and Connections?
Java Tutorial - Using Transactions
Find a sample code HERE with detailed inline comments.