I have a DB schema that creates several tables and fills them with data. I want to check whether db contains corresponding tables or not during app start. I could check for db file existence, but H2 creates db if it doesn't exist. So the only way, I think, is to check for tables existence.
Here is the code of how I initialize DB:
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:database/svc", "sa", "");
Statement st = conn.createStatement();
st.execute("CREATE TABLE IF NOT EXISTS table1 (id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, name VARCHAR(100), record INT, record_date DATE, UNIQUE(name))");
st.execute("CREATE TABLE IF NOT EXISTS table2 (id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, name VARCHAR(100), record INT, record_date DATE, UNIQUE(name))");
st.execute("CREATE TABLE IF NOT EXISTS daily_record_stat (id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, date DATE, table1_id INT, table1_record INT, table2_id INT," +
" table2_record INT, total_record INT);");
st.execute("ALTER TABLE daily_record_stat ADD FOREIGN KEY (table1_id) REFERENCES table1(id);");
st.execute("ALTER TABLE daily_record_stat ADD FOREIGN KEY (table2_id) REFERENCES table2(id);");
st.execute("INSERT INTO table1 VALUES(1, 'non_existed_stub', 0, NULL)");
st.execute("INSERT INTO table2 VALUES(1, 'non_existed_stub', 0, NULL)");
conn.close();
As you see, I check for table existence before creation using IF NOT EXISTS statement. But then I run at the problem with ALTER and INSERT - these commands don's allow IF usage.
I tried to do the following:
Connection conn = DriverManager.getConnection("jdbc:h2:database/svc", "sa", "");
ResultSet meta = conn.getMetaData().getTables(null, null, "table1", null);
if(meta.next()) {
//do something
}
But meta.next() is false.
So how to check whether table schema is initialized? Or maybe this should be done some other way?
Not sure if that's what you mean by saying to check programmatically, buy you can try to use DatabaseMetaData.getTables(). This call will return ResultSet which you'll have to check programmatically. You can see what fields are returned in this ResultSet in corresponding section here. And meta data itself can be obtained by conn.getMetaData().
Following code should return all tables which names start with 'TABLE':
ResultSet meta = conn.getMetaData().getTables(null, null, "TABLE%", new String[]{"TABLE"});
while (meta.next()) {
System.out.println(meta.getString(3));
}
Note that you have to specify table name pattern in upper case. Also it's good to pass table types that you need, although it is optional.
This is a check I used to (re)create the H2 database:
// IMPORTANT A sorted list of table names.
private static final String[] REQUIRED_TABLES = { "USER", ... };
public static final String CREATE_USER = "create table USER (...)";
private boolean schemaExists() throws SQLException {
final List<String> requiredTables = Arrays.asList(REQUIRED_TABLES);
final List<String> tableNames = new ArrayList<String>();
final Connection conn = dataSource.getConnection();
try {
final Statement st = conn.createStatement();
final ResultSet rs = st.executeQuery("show tables");
while (rs.next()) {
tableNames.add(rs.getString("TABLE_NAME"));
}
rs.close();
st.close();
}
finally {
if (conn != null) { conn.close(); }
}
Collections.sort(tableNames);
return tableNames.equals(requiredTables);
}
private void initializeDatabase() throws SQLException {
final Connection conn = dataSource.getConnection();
try {
if (schemaExists()) {
return;
}
final Statement st = conn.createStatement();
st.executeUpdate(CREATE_USER);
conn.commit();
}
finally {
if (conn != null) { conn.close(); }
}
}
And you just call:
initializeDatabase();
Notice the list of required tables has to be sorted because I use List.equals() to compare two lists. It would probably be better to also programmatically sort the required tables list too.
It's not fool-proof (not checking if any table exists and if it should be altered) but it works for me.
Take a look at the SHOW command for other uses.
Related
So I'm trying to add to database using JDBC with HSQLDB from files. And I need to insert the List<Object> as a variable into the database.
This is what it looks like as a Java object:
public class Plant {
private Long id;
private String plantName;
private List<PlantParts> plantParts;
...
}
public class PlantParts {
private String leaves;
private String pedicle;
private String petals;
...
}
In folder resources I have a file called insert_plant.sql that contains this query:
INSERT INTO PLANTS (id, plantname, plantparts)
VALUES (NEXT VALUE FOR sequence, ?, ?);
And the table is generated with this:
CREATE SEQUENCE sequence START WITH 1;
CREATE TABLE PLANTS (
id BIGINT NOT NULL PRIMARY KEY,
plantname VARCHAR(255) NOT NULL,
plantparts VARCHAR(255) NULL, //No idea what to put here
);
And now in Java I am calling this:
public static void insertIntoOrderTable(BasicDataSource basicDataSource, String plantname, List<PlantParts> plantparts) throws SQLException{
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = basicDataSource.getConnection();
stmt = conn.prepareStatement(Util.readFileFromClasspath("insert_plant.sql"), new String[]{"id"});
stmt.setString(1, plantname);
stmt.setString(2, plantparts); //And no idea what to do here
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
The requests will usually come as a JSON:
{ "id": 5,
"plantName": "awesome plant",
"plantParts":[
{"leaves":"green","pedicle":"yellow","petals":"many"},
{"leaves":"red","pedicle":"yellow","petals":"few"}
]
}
My guess is that they should be held in the separate tables, but how can I do that and when I would need to get the object then how could I get it as a whole.
The SQL model of your data will be different from Java in how the Plant and PlantParts objects are linked together. In the Java model, Plant has a collection of PlantParts objects. In the SQL model, the PlantParts objects reference the Plant object.
So you need these two tables:
CREATE TABLE plants (
id BIGINT NOT NULL PRIMARY KEY,
plantname VARCHAR(255) NOT NULL,
);
CREATE TABLE plantparts (
id BIGINT NOT NULL PRIMARY KEY,
leaves VARCHAR(255) NOT NULL,
pedicles VARCHAR(255) NOT NULL,
petals VARCHAR(255) NOT NULL,
plantid BIGINT NOT NULL,
FOREIGN KEY (plantid) REFERENCES plants(id)
);
Note there is no column in the plants table for the PlantParts objects. The data for the PlantParts in your JSON object goes into two rows of the plantparts table. The plantid column of both of these rows will contain the id of the Plant object, which is 5.
So I am creating a JDBC program using a connection. This is my first time becoming familiar with this kind of programming so please excuse me if my question comes across as "dumb". But I have been stuck on this issue for a while. I am created 4 new tables. It compiles fine but when I run it, I get a "ERROR: relation "joke" already exists". When I remove the createTableJoke prepared statement, I get the same error ("ERROR: relation "gift" already exists") for my gift table. This continues for all my statements. What am I doing wrong and what is the logic behind why PostgreSQL does this? I have included my code below:
private static void createTables() throws SQLException {
PreparedStatement createTableJoke = null;
PreparedStatement createTableGift = null;
PreparedStatement createTableHat = null;
PreparedStatement createTableCracker = null;
Connection conn = null;
try {
conn = getDBConnection();
createTableJoke = conn.prepareStatement("CREATE TABLE Joke ( jid INTEGER PRIMARY KEY, joke CHAR(200) NOT NULL, royalty FLOAT NOT NULL);");
createTableJoke.executeUpdate();
createTableGift = conn.prepareStatement("CREATE TABLE Gift ( gid INTEGER PRIMARY KEY, description CHAR(100) NOT NULL, price FLOAT NOT NULL);");
createTableGift.executeUpdate();
createTableHat = conn.prepareStatement("CREATE TABLE Hat ( hid INTEGER PRIMARY KEY, description CHAR(100) NOT NULL, price FLOAT NOT NULL);");
createTableHat.executeUpdate();
createTableCracker = conn.prepareStatement("CREATE TABLE Cracker (cid INTEGER PRIMARY KEY, name CHAR(20) NOT NULL, jid INTEGER REFERENCES Joke(jid), gid INTEGER REFERENCES Gift(gid), hid INTEGER REFERENCES Hat(hid), saleprice NUMERIC CHECK (saleprice > 0), quantity INTEGER NOT NULL);");
createTableCracker.executeUpdate();
} catch (SQLException e){
System.out.println(e.getMessage());
}
finally {
if ((createTableJoke != null) && (createTableGift != null) && (createTableHat != null) && (createTableCracker != null)){
createTableJoke.close();
createTableGift.close();
createTableHat.close();
createTableCracker.close();
}
if (conn != null) {
conn.close();
}
}
}
There are two cases:
You don't care about keeping the existing table if there is one. In this case, issue "DROP TABLE IF EXISTS Joke" before creating it. This will ensure the table is deleted, it will not fail when the table is not there.
You care about the existing content of your tables. In this case, issue a "CREATE TABLE IF NOT EXISTS Joke" ... instead of your plain CREATE TABLE. This will ensure the table is there, and if it already exists, it will not be created. Also note, if you change the structure in your create statement and the table exists, the change in structure does not apply.
This kind of errors means, that all this table were already created. Use pgAdmin (on Microsoft Windows operating systems it usually goes along with PostgreSQL installation) or psql client to connect to the database and check table existence.
I am Retrieving some tables from database and storing those table names in a hashset. Code I am using to retrieve table is as follows
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
hash. add(rs. getString(3) ) ;
}
Now I have tables in a hash set.
Now I want to retrieve data from all these tables in a hash set for particular column 'student'. And put all values in a list. I want to retrieve all distinct values of column student in all these tables. Table may contain or may not contain this student column. If a table contains this column then I want to store its distinct values in a list. Please suggest how to do it.
Note that you can not extract table data using the databasemetadata. Databasemetadata will only provide you the details of table like name, columns, datatypes etc. You need to make the JDBC connection with the database and then need to fire the select query to get the desired result.
Below is the simple JDBC program to do so:
DatabaseMetaData md = conn.getMetaData();
// get tables from database
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
hash. add(rs. getString(3) ) ;
}
// getColumns of table 'tableName'
ResultSet rs2 = md.getColumns(null, null, tableName, null);
boolean found = false;
while (rs2.next()) {
String columnName = rs2.getString("COLUMN_NAME");
if (columnName.equalsIgnoreCase("student")) {
found = true;
break;
}
}
if (found) {
String driver = "provide the driver for database here like com.mysql.....";
String url = "provide the connection url here like jdbc://...."
String userName = "provide DB username"
String password = "provide DB username"
Class.forName(driver)
Connection conn = DriverManager.getConnection(url, userName, password)
Statement st = conn.createStatement();
Resultset rs3 = null;
// Now take the tableName from your hashset and pass it into below query.
String query = "select student from " + tableName;
rs3 = st.executeQuery(query);
While(rs3.next()) {
// Store the results anywhere you want by obtaining 'rs3.getString(1)'
}
}
Hope this resolves your problem. Please ignore typos in code if any.
I'm working with my project just for a academic purposes where I encounter a SQL problem. Where the Foreign Key its not getting the value of inserted ID. For me to achieve 2nd Normal Form. I split out in an independent tables. And match them up using the SECTION_ID as foreign keys. Here where I create a two tables.
1st Table
2nd Table
SOURCE CODE:
String inputSectionName = Section_SectionName_TextField.getText();
int inputStudentLimit = Section_Student_Limit_ComboBox.getSelectedIndex();
String inputRoomAssign = Section_Student_Limit_ComboBox2.getSelectedItem().toString();
String inputAdviserAssign = Section_Student_Limit_ComboBox1.getSelectedItem().toString();
String inputSession = Section_Session_Settings_ComboBox.getSelectedItem().toString();
String inputYearLevel = Section_Session_Level_ComboBox.getSelectedItem().toString();
String inputSchoolYear = Section_SchooYear_ComboBox.getSelectedItem().toString();
String insertALLSECTION_LIST = "INSERT INTO ALLSECTIONS_LIST (SECTION_NAME)"
+ "VALUES (?)";
String insertALLSECTIONS_SETTINGS = "INSERT INTO ALLSECTIONS_SETTINGS (SECTION_POPULIMIT,ROOM_ASSGN,ADVISER_ASSIGNED,SESSION_ASSIGNED,YRLEVEL_ASSGN,SCHOOL_YEAR)"
+ "VALUES(?,?,?,?,?,?)";
try (Connection myConn = DBUtil.connect())//Connection
{
myConn.setAutoCommit(false);//Turn off auto commit
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTION_LIST))//Prepared Statement
{
myPs.setString(1,inputSectionName);
myPs.executeUpdate();
myConn.commit();
}//end of try
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTIONS_SETTINGS))//Prepared Statement
{
myPs.setInt(1,inputStudentLimit);
myPs.setString(2, inputRoomAssign);
myPs.setString(3, inputAdviserAssign);
myPs.setString(4, inputSession);
myPs.setString(5, inputYearLevel);
myPs.setString(6, inputSchoolYear);
myPs.executeUpdate();
myConn.commit();
JOptionPane.showMessageDialog(null, "Insert Successful");
}//end of try
}//end of try
catch(SQLException e)
{
DBUtil.processException(e);
}//end of catch
When I run my query for the 1st Table it gives me output like this.
But when I run my query for the 2nd Table the SECTION_ID column gives a me null value.
Feel free to comment. If I miss something guide me where I go wrong. Thanks.
It looks like you're assuming the SECTION_ID column in your ALLSECTIONS_SETTINGS table will be automatically populated with the last primary-key value that was inserted into the ALLSECTIONS_LIST table. This doesn't happen.
What you need to do instead is to get the value that was automatically generated for the SECTION_ID column in the first PreparedStatement and set it in the second PreparedStatement.
Here's how to modify your first PreparedStatement to obtain the generated SECTION_ID:
int sectionId;
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTION_LIST, Statement.RETURN_GENERATED_KEYS))//Prepared Statement
{
myPs.setString(1,inputSectionName);
myPs.executeUpdate();
myConn.commit();
ResultSet generatedKeys = myPs.getGeneratedKeys();
if (generatedKeys.next()) {
sectionId = generatedKeys.getInt(1);
} else {
throw new SQLException("No generated section ID returned");
}
}
The changes are:
add a new variable sectionId to hold the generated section ID,
add Statement.RETURN_GENERATED_KEYS to the call to prepareStatement on the first line. This tells your database to return the generated value for SECTION_ID.
fetch the generated-keys result-set from the statement and read the section ID out of it..
I'll leave it up to you to modify your second PreparedStatement to set the value for the SECTION_ID column when you insert into ALLSECTIONS_SETTINGS.
I'm working with Java JDBC with Apache Derby data base.
I have a table called `company`` with the values :
id, comp_name, password, email.
This method should create a new row of company with name, password, and email received from the user but the ID should be given automatically from the database and increment itself each time a new company is added to the database.
I just can't figure out how to make this work, I obviously get a error
"column 'ID' cannot accept a NULL value."
because the update occours before the ID is setted.
Code:
public void createCompany(Company company) {
Connection con = null;
try {
con = ConnectionPool.getInstance().getConnection();
String sql = "INSERT INTO company (comp_name, password, email) VALUES (?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, company.getCompName());
pstmt.setString(2, company.getPassword());
pstmt.setString(3, company.getEmail());
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
rs.next();
company.setId(rs.getLong(1));
pstmt.getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionPool.getInstance().returnCon(con);
}
During creation of that table you have to write following DDL
CREATE TABLE MAPS
(
comp_id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(24) NOT NULL,
password VARCHAR(26)
)
Ref : https://db.apache.org/derby/docs/10.0/manuals/develop/develop132.html
You're doing almost everything right, you just need to let the database assign an unique ID to each inserted row:
CREATE TABLE my_table (
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
...
);
A problem could be that you made a mistake by creating your table.
You could create your table like this:
CREATE TABLE company
(
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(50),
email VARCHAR(50),
password VARCHAR (50)
)
IF you want other values to be not NULL you could add NOT NULL to their lines:
password VARCHAR (50) NOT NULL
Delte your old table and execute the the SQl above on your DB. After that you can use your code without changes.