I have made a Database Driven Java Project in which I manipulate the database(Insert/Delete) by java Program.I have to submit it in my university and the condition is that it must run on their computers.The Problem is that they would not have tables/databases i have used.So is there any way to make it poratble i.e. Database Independent or should i give the backup of the databases i used.If yes then how?
-
1In order to make the program portable, it needs to be configurable. You need to able to set the credentials and location of the database. One way to do this would be to read the data from a properties file. Then you could provide bootstraping SQL files that would create the tables and populate data if needed. The other option you have is to use an in-memory database, such as H2 or HSQLgeoand– geoand2014-07-13 12:18:01 +00:00Commented Jul 13, 2014 at 12:18
-
If you ship a database backup with the project, you are indirectly asking your teacher to go and install the very same DBMS you are using on his/her computer, in order to run the application. I would use JavaDB (docs.oracle.com/javadb/10.8.3.0/getstart/…), since it is already a part of the JDK and no additional software is needed in order to run your application.Costis Aivalis– Costis Aivalis2014-07-13 12:21:17 +00:00Commented Jul 13, 2014 at 12:21
2 Answers
Use an embedded database like H2. Simply add the h2-xxxxxx-.jar to your applications classpath and start the database when your programm starts, as described here.
Updated with an example:
Class.forName("org.h2.Driver");
Connection connection = DriverManager.getConnection("jdbc:h2:mem:test-database-name");
// create table, insert data, query for data ...
connection.prepareStatement("CREATE TABLE cars (id INTEGER AUTO_INCREMENT NOT NULL, name CHAR(20));").execute();
connection.prepareStatement("INSERT INTO cars values (null, 'Volkswagen');").execute();
connection.prepareStatement("INSERT INTO cars values (null, 'Audi');").execute();
ResultSet rs = connection.prepareStatement("SELECT * FROM cars").executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1) + " | " + rs.getString(2));
}
The database will be created at line 2 and be destroyed at the end of your programm. Access to this database is exclusive to your programm. You can change the behaviour by changing the connetion url at line 2. Have a look at this table in the docs.
1 Comment
If you just need the database/table structure, you can execute similar SQL commands on your program startup:
CREATE DATABASE IF NOT EXISTS test-database;
USE test-database;
CREATE TABLE IF NOT EXISTS test-table (id BIGINT PRIMARY KEY, ...);
Else you'll need to give your university a backup. Therefore, run
mysqldump -u root -p --database test-database > test_database.sql
in Konsole. A new file test_database.sql is created, in witch are a few SQL commands to create your database. To execute these commands, run:
mysql -u root -p < test_database.sql