JDBC not inserting int jdbc table - java

I am trying to connect java derby db and insert into a table. Everything goes ok but data is not inserted although there is no error at all. Cn you please let me know whats wrong? i tried to change the code and even created new database n table still same. Code works wihtout error but data is not inserted.
Here is my code
databasetest.java
package databasetest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DatabaseTest {
public static void main(String[] args) {
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println(" class found " );
}catch(Exception e){
System.out.println("Not found driver class" + e);
};
try{
Connection conn = null;
String pass =null;
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/user","APP",pass);
System.out.println(" Connected to database " );
try{
Statement st;
System.out.println(" inserted");
conn.close();
}catch(Exception e){
System.out.println(" Eror in inserting" + e );
}
}catch(Exception e){
System.out.println("Mistake happnd " + e);
}
}
}
here is run result
run:
class found
Connected to database
inserted
BUILD SUCCESSFUL (total time: 0 seconds)
Please can some one tell me whats going wrong?
Thanks in advance

The problem seems to reside here: Statement st;. You are creating a statement object but you are not associating any queries to it.
Please take a look at this Oracle Tutorial for more information on the matter.

Your code is not actually trying to insert anything.
Statement st;
System.out.println(" inserted");
conn.close();
This doesn't really do anything other than close the connection.
Usually you will want to create a PreparedStatement with a query like
PreparedStatement st = conn.prepareStatement("place your SQL Query here");
st.execute();
alternatively you could look into the API for PreparedStatement.
If you are set on using a regular Statement or your query is simple and does not involve insecure input, you can use
Statement stmt = conn.createStatement();
stmt.execute("Simple SQL Query here");

from the code looks like You have just created the connection with database.
there is no code to insert something into the database.
add the following code to insert some value into your database.
Statement stmt=con.createStatement();
String query="Insert into table_name values (comma separated sequential column value)"; //here comes your insertion query
ResultSet rs=stmt.executeQuery(query);

Related

Error in using statement in connecting mysql in my java project

screenshot of the codeI want to use statement in connecting mysql and java database, but the code is giving me errors, I want to know where did I go wrong and how I should do it without getting errore
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/sms","root","");
Statement st= (Statement)conn.createStatement();
String sql= "select * from user_login";
}
catch(Exception e){
}![this is the screenshot of the code](https://i.stack.imgur.com/lo8Yo.png)
I tried using this
Alright, so to do JDBC with MySql you need 4 things
Driver Class
Connection URL
Username
Password
Assuming you have already created the database, with name database_name and table data that has 3 columns as id, first_name & last_name
Connection and showing the data in as follows:
import java.sql.*;
import java.util.*;
class ConnectionToDatabase{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","username","Pa$$word");
Statement statement = connnection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from data");
while(resultSet.next()){
System.out.println(resultSet.getInt(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3));
connection.close();
}
}catch(Exception e) { System.out.println(e); }
}
}
And of course, you can use Spring Boot, where a file named application.properties exists inside java.resources, you can specify the connection as - (Copied from Spring docs)
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=databaseusername
spring.datasource.password=databasepassword

HSQLDB not saving updates made through Java

I am trying to add records to a table in an HSQL database through Java.
I have an HSQL database I made through OpenOffice, renamed the .odb file to .zip and extracted the SCRIPT and PROPERTIES files (It has no data in it at the moment) to a folder "\database" in my java project folder.
The table looks like this in the SCRIPT file
CREATE CACHED TABLE PUBLIC."Season"("SeasonID" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,"Year" VARCHAR(50))
All fine so far, the database connects just fine in Java with this code:
public void connect(){
try{
String dbName = "database\\db";
con = DriverManager.getConnection("jdbc:hsqldb:file:" + dbName, // filenames prefix
"sa", // user
""); // pass
}catch (Exception e){
e.printStackTrace();
}
}
I have the following code to insert a record into "Season".
public void addSeason(String year){
int result = 0;
try {
stmt = con.createStatement();
result = stmt.executeUpdate("INSERT INTO \"Season\"(\"Year\") VALUES ('" + year + "')");
con.commit();
stmt.close();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println(result + " rows affected");
}
I have a final function called printTables():
private void printTables(){
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM \"Season\"");
System.out.println("SeasonID\tYear");
while(rs.next()){
System.out.println(rs.getInt("SeasonID") + "\t\t" + rs.getString("Year"));
}
}catch (Exception e) {
e.printStackTrace(System.out);
}
}
Now if I run this sequence of functions:
connect();
printTables();
addSeason("2010");
printTables();
I get this output:
SeasonID Year
1 rows affected
SeasonID Year
0 2010
Now when I close the program and start it again I get exactly the same output. So the change made during the first run hasn't been saved to the database. Is there something I'm missing?
It's caused by write delay params in hsqldb, by default has 500ms delay synch from memory to files.
So problem is solved when it's set to false
statement.execute("SET FILES WRITE DELAY FALSE");
or set as you like based on your app behaviour.
So my workaround is to close the connection after every update, then open a new connection any time I want to do something else.
This is pretty unsatisfactory and i'm sure it will cause problems later on if I want to perform queries mid-update. Also it's a time waster.
If I could find a way to ensure that con.close() was called whenever the program was killed that would be fine...

No results found when querying derby database from program

I am new on working with java(Embedded) databases and derby. I am creating a java application in netbeans ide 8.0. I was able to set up the database and insert data on it. I tried to select rows on one of my db's tables and as expected I saw the rows i inserted. But when i try to select from my code/project, it returns no result. The connection is successfully established as per the logs and no errors encountered. I don't know what to do anymore. :(
Here's my code:
try {
Connection con = DriverManager.getConnection("jdbc:derby:AccountingDB"); /* Note use' / 'and not' \' The url above will be different in your system*/
PreparedStatement stmt = con.prepareStatement("SELECT * from app.companies");
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
companySet.addItem(rs.getString("name"));
//System.out.println("Id : "+rs.getInt(1) +" "+" Fruitname :"+rs.getString(2));
}
else
{
System.out.println("No word matching in database");
}
} catch (SQLException err) {
System.out.println(err.getMessage()+ "No matching word in database");
}
i did this on the customize code of my jComboBox.
thanks. I hope I explained my problem well. :(

can't make updatable resultset with ucanaccess

I've tried most of the examples found here and the web, but I can't open a MS access database(2002 or 2013) and get an updatable result set using UCanAccess. The same code using the JDBC:ODBC driver/connection/works. I've written short test code to check concur_updatable to check this, so I must be missing something. I'm using JDK 1.7 on a Win7 machine. I also have another machine with the same results.
This works:
/*
class jdbc, for testing jdbc:odbc CONCUR_UPDATABLE.
*/
import java.sql.*;
public class jdbc {
private static String dbFQN;
public static void main(String[] args) {
try {
dbFQN = ("C:\\phil\\programming\\kpjl2002.mdb");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + dbFQN;
System.out.println("Loading database: " + database);
Connection conn = DriverManager.getConnection(database, "", "");
Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
// Fetch records from table
String selTable = "SELECT * FROM " + "tblLibrary" + " ORDER BY Artist, Cat, Cart";
s.execute(selTable);
ResultSet rs = s.getResultSet();
int concurrency = rs.getConcurrency();
if(concurrency == ResultSet.CONCUR_UPDATABLE)
{
System.out.println("rs is updatable");
} else {
System.out.println("rs Not updatable");
}
s.close();
conn.close();
} //close try
catch (Exception ex) {
ex.printStackTrace();
} //close catch
} //close main method
} //close dbAccess class
The output is that rs is updatable.
This doesn't work:
/*
class ucan, for testing ucanaccess CONCUR_UPDATABLE.
C:\jdk1.7.0_79\jre\lib\ext\ucanaccess-2.0.9.5.jar
C:\jdk1.7.0_79\jre\lib\ext\hsqldb.jar
C:\jdk1.7.0_79\jre\lib\ext\jackcess-2.1.0.jar
C:\jdk1.7.0_79\jre\lib\ext\commons-lang-2.6.jar
C:\jdk1.7.0_79\jre\lib\ext\commons-logging-1.1.1.jar
also present:
C:\jdk1.7.0_79\jre\lib\ext\commons-logging-1.2.jar
C:\jdk1.7.0_79\jre\lib\ext\commons-lang3-3.4.jar
*/
import java.sql.*;
public class ucan {
private static String dbFQN;
public static void main(String[] args) {
try {
dbFQN = ("C:\\phil\\programming\\kpjl2002.mdb");
String database = "jdbc:ucanaccess://" + dbFQN;
System.out.println("Loading database: " + database);
Connection conn = DriverManager.getConnection(database, "", "");
Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
// Fetch records from table
String selTable = "SELECT * FROM " + "tblLibrary" + " ORDER BY Artist, Cat, Cart";
s.execute(selTable);
ResultSet rs = s.getResultSet();
int concurrency = rs.getConcurrency();
if(concurrency == ResultSet.CONCUR_UPDATABLE)
{
System.out.println("rs is updatable");
} else {
System.out.println("rs Not updatable");
}
s.close();
conn.close();
} //close try
catch (Exception ex) {
ex.printStackTrace();
} //close catch
} //close main method
} //close dbAccess class
the output is that rs is Not updatable. So I cannot update or insert rows in the resultset.
The code posted is the operative part of a larger project, where UCanAccess can read the table and put the contents in a jList and jTextarea, with formatting. When I started writing code to update or add a new record, I ran into the problem.
I apologize if this is a bit long.
Anybody have an idea what I'm missing or doing wrong?
BTW, this is one of my 2 fav sites for good, usable Java answers.
UPDATE:
Got an idea from old co-worker, the original database may have been copied from an original Access97 db. to a 2000 db. I had used 2013 Repair and Compact to make "new" 2002 and 2013 db's. Access must retain '97 type even when doing what I did. So, I created a new 2013 dummy db to test, and UCanAccess will report resultset as updatable. I will try to recreate the record data of the current db in a new database file, and see if that works. I'm hoping this is the problem, since UCanAccess doesn't support updatability with Access97 db's. I'll let ya'll know what I find.
Thanks.
I had used 2013 Repair and Compact to make "new" 2002 and 2013 db's. Access must retain '97 type even when doing what I did. So, I created a new 2013 dummy db to test, and UCanAccess will report resultset as updatable.
The "Compact and Repair Database" feature in Access does not change the database file version. If you have (what you suspect to be) an older-version database file then you should use the "Save Database As" feature under "File > Save & Publish" * to convert the database file to a newer version.
* (... at least that's where it is in Access 2010.)
Well, after a nice weekend of eating brats and drinking good beer at Germanfest, I finally got things working. I decided to scrap the MS Access db and put the 472 records in a SQLite db. With that, I was able to get PreparedStatements to work to display the records in a jList and JTextArea, add a new record and update a couple fields in an existing record within the same run of the test application. Did it both as a command line run GUI and from NetBeans 8.0, so I think my problems are solved. After a couple of summer projects get done, I'll get back to re-writing the original VB app using Java.
Thanks Gord, and everyone here.

Closed Connection: next in java

I have ResultSet Methods which I am closing the Connection in a finallly Block:
public static ResultSet countdrcountcr(String vforacid) throws SQLException {
ResultSet rs = null;
Connection conn = null;
try {
conn = db.getDbConnection();
String sql = "SELECT NVL (SUM (DECODE (part_tran_type, 'D', 1, 0)), 0), "
+ " NVL (SUM (DECODE (part_tran_type, 'C', 1, 0)), 0) "
+ " FROM tbaadm.htd WHERE acid IN (SELECT acid "
+ " FROM tbaadm.gam WHERE foracid = '" + vforacid + "') "
+ " AND tran_date >= '22-NOV-2013' AND tran_date <= '30-NOV-2013' "
+ " AND pstd_flg = 'Y' AND del_flg != 'Y'";
PreparedStatement ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
return rs;
} finally {
conn.close();
}
}
But I am getting the error :
edit The whole ErrorTrace
Exception in thread "main" java.sql.SQLException: Closed Connection: next
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.OracleResultSetImpl.next(OracleResultSetImpl.java:181)
at statement.Statement.main(Statement.java:34)
Java Result: 1
What am I not doing right?
You're returning a ResultSet for future use but after using it you're closing the connection, so you have no way to retrieve the data since the resource is already closed. Note that finally is always called, even if you return something in the try or catch code block, refer to Does finally always execute in Java?
In detail, this is the problem:
Open the connection
Prepare a statement
Get the result set
Return the result set
Close the connection (that may close the associated resources i.e. it may close the PreparedStatement and the ResultSet associated with the current Connection) because, as noted in the link before, finally block is always executed at least that the JVM crashes or you manually finish the application using System.exit.
Using a closed ResultSet. It is closed due to the previous step.
A possible solution would be that your countdrcountcr method and all other methods that return a ResultSet receive the Connection as parameter, so the method that calls it will handle the connection opening and closing. Also, take note that you should not use static methods to handle your database operations if you're working in a multi threaded environment e.g. a web application.
I think your query is taking a long time to execute and getting terminated by the driver/tomcat level.
Check you application context xml file for parameter removeAbandonedTimeout value.
removeAbandonedTimeout=300
means, if any query running for more than 300 seconds will be close by the JDBC driver. This is done to avoid connection pool "leak". To fix this you can set the value with some higher number.
More info about this param and other related parameters can be found here
You're closing the underlying Connection in your finally block... You're not closing the PreparedStatement (and you should, but you need to close that after you use your ResultSet too). use the finally block of the caller (where you open the Connection). Also, you might want to consider using setFetchSize().
You cannot close a Connection then use the ResultSet. You have to finish using the ResultSet first, then close the Connection sometime after. The normal pattern is to finish your work with the ResultSet first, usually in a "Data Access Object", and return some encapsulated representation of the data as an object.
If u tryied to close the connection inside the while block that time also u can get this kind of exception...so close the connection after the while block
package com.literals;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DataBaseDemo {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("driver is loading...........");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:mytest","SYSTEM","murali");
System.out.println("connection is established");
Statement st=con.createStatement();
System.out.println("statement is created");
ResultSet rs=st.executeQuery("select * from student");
while(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getInt(2)+" "+rs.getString(3)+"");
con.close();
}
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Like say above: Also, take note that you should not use static methods to handle your database operations if you're working in a multi threaded environment e.g. a web application.
That really help.
Luiggi's answer is correct but it seems like what the OP didn't understand was why closing the connection prevented the ResultSet from working, since the code got the ResultSet before the connection closed.
There's a popular misunderstanding that a ResultSet must be some kind of data-holding object that you can use to pass stuff around in. It isn't. it's just a reference to a database cursor, it hasn't actually fetched the data for a row until you call next() on it. It needs a live connection in order to work. You need to unpack your results from the query into a collection (usually a list) before you close the connection.
BTW, don't add parameters to your SQL with string concatenation, it opens you up to SQL injection (and also handles quoting the parameters is a pain). You can add ? to your SQL and add values for the parameters by calling methods on the preparedStatement.
If you use Spring JDBC it will handle all the tedious JDBC stuff for you (including closing everything that needs to be closed), and all you have to handle is implementing a RowMapper to describe how to move data from the ResultSet into the collection.
I had a similar problem where my connection was being closed inside a while loop, so the condition could not be checked in the next round. To fix, I placed con.close(); outside the loop and this resolved the issue. Like this:
while (rs.next()) {
String name = rs.getString("NAME");
}
con.close(); //placed outside the loop
}

Categories