27.10.2013 Views

Jaybird 2.1 JDBC driver Java Programmer's Manual - Firebird

Jaybird 2.1 JDBC driver Java Programmer's Manual - Firebird

Jaybird 2.1 JDBC driver Java Programmer's Manual - Firebird

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

tables using the above mentioned method.<br />

Statement stmt = connection.createStatement();<br />

try {<br />

DatabaseMetaData metaData = connection.getMetaData();<br />

ResultSet tables = metaData.getTables(<br />

null, null, "customer", new String[]{"TABLE"});<br />

if (!tables.next())<br />

stmt.execute("CREATE TABLE customer(" +<br />

"customerId INTEGER NOT NULL PRIMARY KEY, " +<br />

"firstName VARCHAR(20) NOT NULL, " +<br />

"lastName VARCHAR(40) NOT NULL)");<br />

} finally {<br />

stmt.close();<br />

}<br />

Illustration 4.3: Example of creating database tables.<br />

First, application checks the existence of the table in the database by calling the<br />

DatabaseMetaData.getTables(String, String, String, String[])<br />

method that returns a result set describing the database tables matching the<br />

specified search pattern. First two parameters of this method, the database catalog<br />

and schema names, are set to null as <strong>Firebird</strong> supports neither catalogs nor<br />

schemas. Third parameter is the table name search pattern, in our case we search<br />

for the table "customer". Last parameter is the list of table types to check, in our<br />

case we check for the "TABLE" type. Other tables types are "SYSTEM TABLE" and<br />

"VIEW".<br />

After that application checks if the result set is empty by calling the<br />

ResultSet.next() method. If no "customer" table was found, application<br />

creates new table with three columns.<br />

As it was already mentioned, the Statement.execute(String) method can also<br />

be used to execute statements of the unknown type.<br />

Statement stmt = connection.createStatement();<br />

try {<br />

boolean hasResultSet = stmt.execute(sql);<br />

if (hasResultSet) {<br />

ResultSet rs = stmt.getResultSet();<br />

...<br />

} else {<br />

int updateCount = stmt.getUpdateCount();<br />

...<br />

}<br />

} finally {<br />

stmt.close();<br />

}<br />

It is worth mentioning, that according to the <strong>JDBC</strong> specification getResultSet()<br />

and getUpdateCount() methods can be only called once per result, and in case of<br />

using <strong>Firebird</strong>, that means once per executed statement, since <strong>Firebird</strong> does not<br />

support multiple results from a single statement. Calling the methods the second<br />

time will cause an exception.<br />

Chapter 4. Executing statements 36

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!