Java resultSet.updateRow() doesn't update database - java

Sorry if my question is trivial but I am new to Java programming.
I have a following problem:
I created a derby database using NetBeans IDE (I went to Services tab -> JavaDB -> create database). Then I created my java project and added reference to derbyclient.jar.
Using these arguments:
String host = "jdbc:derby://localhost:1527/Employees";
String username = "jarek";
String pass = "aaa";
I managed to create jdbc Connection and was able to populate ResultSet with data from table Employees. Next I wanted to update database using this result set so I wrote:
rs.absolute(rowtoupdate);
rs.updateObject("FIRST_NAME", updatedvalue);
rs.updateRow();
and everything worked fine (data was actually updated in database).
Now to my problem. I wanted this database to be embedded in my application so I copied its files into foleder "DB" in my project's location (I copied Employees folder as well as derby.log and derby.properties). I changed referenced in project jar file from derbyclient.jar to derby.jar. After that I used different arguments:
String host = "jdbc:derby:DB//Employees";
String username = "jarek";
String pass = "aaa";
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName( driver );
connection = DriverManager.getConnection( url, username, password );
Again I was able to populate resultSet with data from database (so everything seems to work) but when I try to perform exact same update:
rs.absolute(rowtoupdate);
rs.updateObject("FIRST_NAME", updatedvalue);
rs.updateRow();
changes aren't kept in database.
What am I doing wrong? Can it be caused by me copying database files to my project's location? But then again resultSet after running a query on Statement contains proper data from database so it seems to work...

Calling connection.commit() solves the problem.

Related

Set relative path using jdbc, on a sqlite DB on user computer

I'm trying to build a simple java application for my school project, and I want to be able to use a simple DB, in order to insert, update, delete and ask queries on my DB.
I need my application to run everywhere on installation, so I want to use a local DB that ships with my application, and will be accessible from inside the project, without different DB dependencies
so I've read a little and found this SQLite tutorial -http://www.sqlitetutorial.net/sqlite-java/sqlite-jdbc-driver/
,
now I want to set a relative path to the user who download my application, and set the connection on the user computer. I've noticed it's written :
connect to an in-memory database, you use the following connection string:
jdbc:sqLite::memory
here is my code:
public class Main {
public static void main(String[] args) {
try{
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Desktop\\School Project\\Software-Engineering---Java-Project\\data.db");
Statement statement = conn.createStatement();
//CREATE TABLES
statement.execute("CREATE TABLE IF NOT EXISTS CUSTOMERS (name TEXT,phone INTEGER,email TEXT)");
//INSERT TO TABLES
statement.execute("INSERT INTO CUSTOMERS (name,phone,email)" +
"VALUES ('NETANEL', 05555555,'SADF#GMAIL')");
notice how my JDBC is the path to my local computer, how can I change this?
EDIT:
I'm able to set the path with only referring the DB name:
final static String DB_URI = "jdbc:sqlite" + ":data.db";
public static void main(String[] args) {
try{
Connection conn = DriverManager.getConnection(DB_URI);
Statement statement = conn.createStatement();
the question is, will it be cross platform if i will deploy my application with this DB?
You can use the user home directory. You are sure it's always defined whatever platform you deploy your program on, and your program will have read/write access to it.
Something like this:
String dbUri = "jdbc:sqlite:" + System.getProperty("user.home") + "/data.db";
Connection conn = DriverManager.getConnection(dbUri);

SQLite error or missing database (no such table) in Netbeans connection to SQLite

I am getting the above error when trying to do an insert(or select) to a SQLite file from Java in Netbeans. I have created the db file manually from SQLite Database Browser and put it in the source package. Below is the code and logs:
public void DBInsertServerConfig(ServerConfig serverconfig) throws SQLException {
Connection conn = DBConnect();
Statement statement = null;
conn.setAutoCommit(false);
statement = conn.createStatement();
String sql = "INSERT INTO serverconfig(ip,port,db_name,db_user,password,fcm_server_key) " +
"VALUES (?,?,?,?,?,?)"; //
try{
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1,serverconfig.getIp());
pstm.setString(2,serverconfig.getPort());
pstm.setString(3,serverconfig.getDb_name());
pstm.setString(4,serverconfig.getDb_user());
pstm.setString(5,serverconfig.getPassword());
pstm.setString(6,serverconfig.getFcm_server_key());
//statement.execute(sql);
pstm.executeUpdate();
statement.close();
conn.commit();
conn.close();
The database is opened correctly but it seems it doesn't find the table although it exist.
compile:run:
Opened database successfully
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: serverconfig)
BUILD SUCCESSFUL (total time: 9 seconds)
Attached is a screenshot of the db file from SQLite Database Browser :
I have seen and tried other posts like in here but I didn't get a solution.
Can anyone help me figuring out this?
I found the answer and I am posting if anyone run into the same problem/confusion.
I had put my db file under the src package while the url path was pointing into the project root folder(outside src). An empty db file was created by netbeans, and of course it hadn't any table in it. That's what happen when you follow tutorials that haven't been tested by their own creators. :D
The example that I used was
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Tolga\\Documents\\NetBeansProjects\\dpmlzmtkb\\depom.sqlite");
Which is wrong.
I changed depom.SQLite to depom.db and it worked. So as I understand if the path is correct NetBeans creating another empty SQLite database to the given path.
Please use the absolute path,like(on my Ubuntu)
private static String url ="jdbc:sqlite:/home/yourname/study/eclipse/hk/ss.db";
At first i get same error like yours,
i can link sql in ordinary class,but in the servlet/jsp can't

Creating/Configuring Derby JDBC Client in IntelliJ Idea 13

Sorry for this (maybe) stupid question.
I need to create some local DB in my java project so I've decided for Apache Derby Client. I am working with IntelliJ IDEA 13 Ultimate and my problem is that I don't know, how to create local database.
Tutorials at Jetbrains websites aren't useful because there are articles only about connecting to the remote DB, not to the local one (or at least I didn't find them yet).
What have I done so far:
I've tried to set the DB up by creating new remote derby data source.
Screenshot with the settings: DB Settings screen
Username and password are the same: admin
After clicking test connection, this error is thrown: error
When I click apply and ok, it says that it's connected, but exception is still there.
So do you have any idea where the problem can be?
I've got small confiuration class called DatabaseSetting.java
package issuetrackinglite;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseSetting {
private String dbURL = "jdbc:derby://localhost:1527/MallDB;create=true";
private String user = "admin";
private String password = "admin";
private Connection connection;
public static final String CREATE_ITEMS_DB = "CREATE TABLE items (item_id INTEGER NOT NULL, item_name VARCHAR(20) NOT NULL, item_price REAL NOT NULL, multiplicity_shop INTEGER NOT NULL, multiplicity_store INTEGER NOT NULL)";
public static final String INSERT_PRODUCT = "INSERT INTO items (item_id, item_name, item_price, multiplicity_shop, multiplicity_store) VALUES (?, ?, ?, ?, ?)";
public static final String CLEAR_ITEMS_DB = "DELETE FROM items";
// -------------------------------------------------------------
protected Connection connectToDB() {
try {
connection = DriverManager.getConnection(dbURL, user, password);
return connection;
} catch (SQLException ex) {
System.out.println("SQL exception - connectToDB(): " + ex.getMessage());
return null;
}
}
}
EDIT
Simply explained: I just need to create virtual derby database which will be created every time at the program start.
I don't know, how to do it in IntelliJ.
I've added DERBY_HOME to the enviroment variables and also added path to Derby. Now this error is thrown by IntelliJ: Error window
Thank you very much for your help and time
I've managed to get this work. Here are the steps that I've made to successfully configure local Derby database to work in IntelliJ Idea 13/14.
First, you need to manually start derby server (if it is not already running) before using it in IDEA. I usually do it via command prompt by typing:
C:\Users\PcName>startNetworkServer -noSecurityManager
This command will start derby server on port number: 1527. Make sure you have correctly set path in enviroment variables
Next go to IDEA, open Database window, click on the green plus sign in the upper left corner and in the dropdown menu choose: Data Source -> Derby -> Remote
You can inspire with my settings provided in the screenshot in my question. You can also download Derby driver files. IDEA does it just by clicking on the download button.
Basic template which I always use is something like that:
Name field should be in the form: Derby - YourDatabaseName;create=true#localhost
Host field should have localhost inside
Port has to be 1527
Database field has to be in form: YourDatabaseName;create=true
Urc to connect: jdbc:derby://localhost:1527/YourDatabaseName;create=true
(Optional) - You can specify your database user name and password. In IDEA 14 there is a checkbox Save on disk with master password protection, which I personally always leave unchecked.
That's it. I hope this little guide will help somebody to configure Derby in Intellij IDEA
For embedded database, use the default/In-Memory/URL only select box on the right side of the connection URL input field. When set to In-Memory, it generates the following URL, which works for me.
jdbc:derby:memory:MallDB;create=true
I think that for a local (embedded) database, you would leave off the host and port in the connection url.
The documentation says that the url should be of the form: jdbc:derby:MallDB;create=true

Connecting to Oracle with JDBC causes queries to return zero rows.

So I have been playing around with querying databases using the standard
Statement s = connection.createStatement();
ResultSet rs = s.executQuery(queryString);
ResultSetMetadata rsmd = rs.getMetaData();
while(rs.next)){
String code = "";
String value = "";
for(int i = 1; i <= rsmd.getColumnCount(); i++){
Object obj = rs.getObject(i);
if(i == 1){
code = obj.toString():
}
else{
label = obj.toString();
}
}
//Store code and labels in map
}
...go on to close statement and move on.
I am trying to select two columns from a table in each instance.
For the most part this works well. When working with MySql & Microsoft Sql databases I get a result set full of data in the table. However when I try to do this with an Oracle database I get an empty result set.
I have tested my query string in the SQL Developer application and it works fine, returns my data. But the result set doesnt contain anything. The resultSet metadata says that it has two columns though. Is there anything I need to do when interacting with an Oracle Database that is different from the other two? Thanks.
If your query works when you run it against the Oracle database, and you know the code works since you've run it against MySQL, then some other things to try are:
1.) Make sure your JDBC connection URL is correct. Are you sure you are connecting to the database that you intend to? (i.e. - the one that would return the rows you expect?)
2.) Take into account credentials. Make sure you are using the same credentials through JDBC that you are when connecting to Oracle directly.
3.) Make sure both connections are being made from the same machine and with the same environment. Oracle drivers rely on environment variables to find a file (I believe it is called tnsnames.ora, or something like that) that contains the alias & connection info. Getting different versions of that file could point you to different Oracle instances.
4.) Try manually specifying your schema name in the query. So instead of select * from my_table use select * from my_schema.my_table. Sometimes Oracle clients will configure their sessions to have default schemas set up in their preferences.
5.) If your are attempting to select data that you've inserted with your Oracle client, make sure you've committed the transaction in your Oracle client so that the data is visible to other sessions.
One last debugging tool to use is to try connecting via the Squirrel DB client. Squirrel is a 100% pure java SQL client that connects to any DB using JDBC. It would be a good test to make sure your JDBC Driver, Connection URL, etc. are all valid.
The database table has records but the JDBC client can't retrieve the records. Means the JDBC client doesn't have the select privileges. Please run the below query on command line:
grant all on emp to hr;

Cannot read an SQLite Database made in another language

I have an SQLite3 databse I created in python. And by default it writes the database in Unicode.
Now I am trying to query the database in a Java Applet using SQLite JDBC. And I cannot find tables, rows etc because I think Java &/or JDBC queries in ANSI.
Does anyone know how I can query my SQLite3 DB with a unicode query in Java? Something like the following doesn't work (in Java trying to execute a Unicode SQL query):
If I access the database in python I can print out the tables no problem & make updates BUT if I try to do the same in Java, I get no results returned from my query. Is this an encoding problem or some thing else
This works import sqlite3
def blah():
conn = sqlite3.connect( "a.db" )
cur = conn.cursor()
res = cur.execute( "SELECT name FROM sqlite_master WHERE type='table'" ).fetchal()
print res
blah()
This returns no tables when it should return the same tables as above
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:a.db");
Statement stat = conn.createStatement();
conn.setAutoCommit(false);
ResultSet tables = stat.executeQuery("SELECT name FROM sqlite_master WHERE type='table'");
String b = "";
while (tables.next()) { b+= "table= " + tables.getString("name"); }
Jim, that's very odd, it should work. Have you tried to open the DB from the console?
you can open it by running sqlite3 a.db
something that intrigues me, is that you're trying to open the db from a java applet. Have you given it the necessary permissions and signed it, so the apple can actually write to disk?
Have your tired opening the sqlite3 a.db and typing PRAGMA encoding; ? It should say UTF8 by default.
I am able to create a UTF8 sqlite database on the command line and read the contents of that file using sqlite jdbc.
Are you sure you are connecting to the database that you created with python? IF the database does not exist then sqlite will create the database and it will not have any tables in it. This is what is probably happening to you.
Are you running the java and python in the same directory?

Categories

Resources