-1

I'm trying to create a table in mysql through java. I'm using putty for this by the way. Here is a bit of the code I have so far but it doesn't work.

rs=s.executeQuery("CREATE TABLE test(id CHAR(2),name VARCHAR(3),PRIMARY KEY(id)); ");
while(rs.next())
{
  System.out.println(rs.getString(1));
}
catch (SQLException ex)
{
  System.out.println("SQLException:"+ ex.getMessage());
}

4 Answers4

1

executeQuery() is for quires (usually SELECT) that return a ResultSet.

With DML (and DDL) queries you need to use executeUpdate() method.

For more information and examples use Setting Up Tables tutorial.

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
0

See this post here: Data Manipulation Statements

You should be using executeUpdate() if you wish to actually modify the database.

Community
  • 1
  • 1
Sean M.
  • 118
  • 5
0

Your query is ok! But you don't get a result set! the CREATE TABLE won't give an rows or columns. You have been tricked be the documentation:

Returns: a ResultSet object that contains the data produced by the given query; never null

however

Throws: SQLException - if a database access error occurs,... the given SQL statement produces anything other than a single ResultSet object, ...

In my opinion a call of "execute" would be the proper way.

Joachim Weiß
  • 407
  • 2
  • 12
0

I don't think its ever a good idea to generate your database schema via Java. Use the utility tool that comes with your database to create your schema. This way, you or anyone (such as a DBA) can create your tables, views, indexes, constraints, grant permissions, etc without having to know Java. You can even have your database utility generate an SQL script that you can run to re-generate the schema from scratch. Last point: I believe you will be better off calling your primary key test_id and making it type numberic, long, or int. this way, when you refer to it as a foreign key in another table, you will immediately know it refers back to the test table.

user2810910
  • 279
  • 1
  • 2