tags:

views:

85

answers:

2

I want to create a table containing three string columns:

  1. The JSP page
  2. Part of JSP page (like footer, header, text)
  3. Actual value text

How do I do that:

  1. from the command prompt
  2. from a Java application (Create if it doesn't exist -- how common is that?)

Thanks

+2  A: 

It is not likely you would want to create a table dynamically, especially if you need to save data and get it during other sessions. It's best to use mysql command prompt or a graphical tool like SQL Yog to create a table that you will later access at JSP page.

The command to create table will look like this

CREATE TABLE `pages` (
  `id` int(11) NOT NULL auto_increment,
  `part_of_page` varchar(30) NOT NULL,
  `actual_text` varchar(300) NOT NULL,
  PRIMARY KEY  (`id`)
) CHARACTER SET `utf8`;
PHP thinker
Why is ID primary key?
vehomzzz
please don't say `NOT NULL default ''`, but instead, just say `NOT NULL`. This way, the database will give an error if you try to insert empty data.
hhaamu
+1  A: 

As PHP Thinker says, you rarely want to create a table dynamically within a program. But if you have a legitimate reason, you just submit the "create" statement like an update query:

try
{    
Statement st=conn.createStatement();
    st.executeUpdate("create table mytable ... whatever ...");
    st.close();
}
catch (SQLException oops)
{
   ... query had syntax errors or something  ...
}

This is an update and not a query so there is no ResultSet returned. The return value is the number of records updated, which for a "create table" is always zero so no point bothering with it. If there's an error in

Jay
+! How about create if it doesn't exist?
vehomzzz
The only trick is to check whether it already exists. I don't know of any generic SQL way to ask if a table exists, but a generic Java way would be to use Connection.getMetaData() to get a DatabaseMetaData object for your database, then do getTables(null, null, "mytablename", null) and if you get anything back, the table exist. (Use non-null values for the other parameters if necessary to avoid ambiguity -- see the JavaDocs.)Most SQL engines now support the "information_schema", so you could query against that. But I think the DatabaseMetaData method is cleaner.
Jay