1 package org.backsource.utils.sql;
2
3 import java.sql.Connection;
4 import java.sql.SQLException;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7 import java.sql.DatabaseMetaData;
8
9 /***
10 * A collection of static utility methods to work with jdbc metadata.
11 *
12 * @author <a href="mailto:jens.askengren@tim.se">Jens Askengren</a>
13 * @version $Id: MetadataUtil.java,v 1.1.1.1 2004/05/19 12:07:31 pra Exp $
14 */
15
16 public class MetadataUtil
17 {
18
19 /***
20 * Check if a table exists in the database.
21 *
22 * @returns true if the table @param tableName exists
23 * @throws SQLException
24 */
25 public static boolean tableExists(Connection con, String tableName)
26 throws SQLException
27 {
28 boolean exists = false;
29 ResultSet rs = null;
30
31 try {
32 DatabaseMetaData dmd = con.getMetaData();
33 rs = dmd.getTables(con.getCatalog(), null, tableName, null);
34 if (rs.next ()) {
35 exists = true;
36 }
37
38 } finally {
39 try { rs.close(); } catch (Exception e) {}
40 }
41
42 return exists;
43 }
44
45 /***
46 * Check if the table exists. If not, it will be created
47 * <p>
48 * <em>This method does only check if the table name exists. It does
49 * not check that the table actually matches the create statement</em>
50 * </p>
51 *
52 * <p>
53 * <b>Example</b>
54 * <code><pre>
55 * MetadataUtil.checkCreateTable(con,
56 * "Customer",
57 * "CREATE TABLE Customer ("
58 * + " Id INTEGER,"
59 * + " Name TEXT"
60 * + ")");
61 * </pre></code>
62 * </p>
63 *
64 * @param tableName name of table
65 * @param createStatement table definition.
66 * @throws SQLException
67 */
68 public static void checkCreateTable(Connection con, String tableName, String createStatement)
69 throws SQLException
70 {
71 PreparedStatement pst = null;
72 try {
73 if (!tableExists(con, tableName)) {
74
75 pst = con.prepareStatement(createStatement);
76 if (pst.executeUpdate() != 1) {
77
78
79
80
81
82 }
83 }
84 } finally {
85 try { pst.close(); } catch (Exception e) {}
86 }
87 }
88
89 }