H2 provides a BACKUP command that can be used from a SQL statetement and creates a backup file:
String url = "jdbc:h2:nioMemFS:atestdb";
try (Connection con = DriverManager.getConnection(url);
Statement s = con.createStatement()) {
s.execute("CREATE TABLE test_table ( test_values VARCHAR(255) )");
s.execute("INSERT INTO test_table (test_values) VALUES ('abc'), "
+ "('def'), ('hji')");
s.execute("BACKUP TO 'backup.zip'"); // writes to backup.zip
}
This also works for in-memory databases (edit: it works with the nioMemFS file system but not with plain in-memory databases; see Oleg`s answer below). Is there also a command for restoring such a database file?
Thanks!
The BACKUP command shouldn't work for in-memory database, when I try I get DATABASE_IS_NOT_PERSISTENT error, if the backup command works for you, you're probably not using a persistent database.
You can use the SCRIPT and RUNSCRIPT to backup and restore respectively via creating and running an sql script from the database.
SCRIPT TO 'backup.sql';
RUNSCRIPT FROM 'backup.sql';
Related
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
Hi I would like to create table through JDBC on multiple databases like DB2, Sybase, MySQL etc. Now I need to create this table using text file say data.txt which contains data space separated values. For e.g.
CustName OrderNo PhoneNo
XYZ 230 123456789
ABC 450 879641238
Now this data.txt contains thousands of records space separated values. I need to parse this file line by line using java io and execute sql insert queries for each records.
I found there is LOAD DATA INFILE sql command. Does any JDBC driver supports this command? If not what should be the best efficient fast approach to solve this problem.
Please guide. Thanks in advance.
The following will work through JDBC. Note that to use LOAD DATA INFILE you need superuser privilege. Which you don't need for LOAD DATA LOCAL INFILE
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/foobar", "root", "password");
Statement stmt = con.createStatement();
String sql =
"load data infile 'c:/temp/some_data.txt' \n" +
" replace \n" +
" into table prd \n" +
" columns terminated by '\\t' \n" +
" ignore 1 lines";
stmt.execute(sql);
If you use LOAD DATA INFILE the file location is based on the server's filesystem! If you use a local file, then obviously it's based on the client's filesystem.
I think LOAD DATA INFILE is specific to mySql, and I doubt whether a JDBC driver would support it. Other databases will have similar ( but different ) utilities
If you want to do this is a database independent way I think you have two choices
Parse up the input file and use SQL INSERT statements over a JDBC connection
Write a number of different, database dependent scripts, determine which dbms you are using and execute the correct one using Runtime.exec
Unless you have compelling performance reasons not to, I'd go for option 1.
I believe LOAD DATA INFILE is faster than parsing the file and inserting the records using Java . You can execute the query for load data infile through JDBC. As per this Oracle doc and MySql doc:
The LOAD DATA INFILE statement reads rows from a text file into a table at a very high speed.
The file should be in server . You can try both the approaches, log the time each one of them consume.
"Load data local infile" does work with MySQL's JDBC driver, there are some issues with this.
When using "load data infile" or "load data local infile" the inserted records WILL NOT be added to the bin log, this means that if you are using replication the records inserted by "load data infile" will not be transferred to the slave server(s), the inserted records will not have any transactions record, and this is why load data infile is so much quicker than a standard insert and due to no validation on the inserted data.
I have java code that connects to a remote oracle 11g EE db server. If i run a particular query in sqlplus it returns one result
SQL> SELECT COURSENAME from COURSES where skillID=1;
COURSENAME
--------------------
basic
But if I run the same query from the java code below it returns no results. I can copy the query syntax out of the query variable in the java debugger and running it on oracle so I know there is no syntax issue with the query. Also, it is not SQL exceptions or class not found exceptions so it seems to be running the query successfully -- just returning zero results.
What might be going on?
private String getCourseForSkill(int skillID){
try{
Class.forName("oracle.jdbc.OracleDriver");
String query="SELECT COURSENAME from COURSES where skillID=" + skillID ;
con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
rs = stmt.executeQuery(query);
rs.next();
return rs.getString("COURSENAME");
}
catch (ClassNotFoundException ex){
System.out.println(ex.getMessage());
}
catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return null;
}
I think you're connecting to different Oracle instances, or more likely, as different Oracle users in the two cases
#GreyBeardedGeek the URL looks like "jdbc:oracle:thin:#website:port:orcl I get to the manual query by doing ssh#website, authenticating and then running command=sqlplus
Safer to run sqlplus <username>/<password>#<orainstancename>, because you can explicitly specify the oracle instance ID. In your case, it seems your program is using jdbc connection jdbc:oracle:thin:#website:port:orcl, so your orainstancename would be 'orcl' - just ensure that your tnsnames.ora file has the instance 'orcl' with the same 'port' as used by the jdbc connection
How to debug a little more
Run the following code:
con = DriverManager.getConnection(url, user, password);
con.setAutoCommit(false);
String insert="INSERT INTO COURSES (SKILLID, COURSE)"+ // can add other columns
"values (?, ?) );" // add ? for other columns
PreparedStatement ps = con.createPreparedStatement();
ps.setInt(1, 999);
ps.setString(2, "Complete Bullwarks");
// can set other columns
ps.executeUpdate(insert);
con.commit();
NOW connect manually, re-run your original select statement & see if the added row is there. If no error in java and no new row in Oracle: extremely likely you're using 2 different Oracle instances/schemas.
ALSO rerun your original java select code, but with SkillID=999 - extremely likely it will work.
Cheers
I had to do a commit to add the rows. When I typed commit; into the sql plus terminal then the remote jdbc connection could 'see' the rows. I am used to SQL server where you don't have to explicitly do these kinds of commits when using linq-to-sql or sql management studio.
It can be three issues.
1) skillID <> 1 in your Java code. Add debug and check.
2a) You are connecting to another database.
2b) You are connecting to the same database but SELECTING from a table in another schema.
To check 2a and 2b:
select user from dual; -- connect username
select name from v$database; -- database name
select host_name from v$instance; -- host name database is running on
This query returns all three into one result.
select user || '' || d.name || '' || i.host_name
from v$database d, v$instance i;
Assuming you are actually connecting to the same database this is caused by not committing the INSERT in the sql*plus connection.
Oracle by default does not run in auto-commit mode when connecting via OCI (which sql*plus uses to connect). Any DML(INSERT ...) executed in sql*plus will not be visible to any other session until it is committed. This is because Oracle provides a read committed isolation level by default. The only thing visible to other users across sessions are write locks.
It doesn't matter if you connect the second connection via JDBC or OCI, it won't see the changes till you commit the first connection.
To test this out try opening 2 sql*plus connections and run the following:
-- Executing DDL in Oracle causes an implicit commit before and after the
-- command so the second connection will see the existence of this table:
CREATE TABLE foobar ( x VARCHAR(1) );
Execute this in connection #1 - you should get zero (we haven't inserted anything yet):
SELECT COUNT(*) FROM foobar;
Execute this in connection #2:
INSERT INTO foobar ( x ) VALUES ( 'A' );
Execute this in connection #1 - you should still get zero (INSERT is not committed so connection #1 cannot see it):
SELECT COUNT(*) FROM foobar;
Execute this in connection #2:
COMMIT;
Execute this in connection #1 - you should get 1 (it's committed now):
SELECT COUNT(*) FROM foobar;
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.
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?