title: Using a java class to create a database
body: <p>I'm working in an application that uses servlets and mysql.</p>
  
  <p>I'd like to create a .jar file able to create the database that the application will be using. This will only be done once, in order to create the db.</p>
  
  <p>I've no problem in getting to access to a database, doing something like this:</p>
  
  <pre><code>Class.forName("com.mysql.jdbc.Driver").newInstance();
  Connection conexion = (Connection)DriverManager.getConnection("jdbc:mysql://localhost/test","admin","admin");
  if (!conexion.isClosed())
  {   
     Statement st = (Statement) conexion.createStatement();
     ResultSet rs = st.executeQuery("select * from table_name" );
  }
  conexion.close();
  </code></pre>
  
  <p>This is ok, but what I need to do is to create a new database (and its tables) from a java class, is that possible?</p>
  
  <p>I'm trying this:        </p>
  
  <pre><code>Class.forName("com.mysql.jdbc.Driver").newInstance();
  Connection conexion = (Connection)DriverManager.getConnection("jdbc:mysql://localhost/mysql","admin","admin");
  
  Statement st = (Statement) conexion.createStatement();       
  st.executeUpdate("CREATE DATABASE hrapp");
  </code></pre>
  
  <p>but I'm getting the following error:</p>
  
  <pre><code>Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user 'admin'@'localhost' to database 'hrapp'
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
      at java.lang.reflect.Constructor.newInstance(Unknown Source)
      at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
      at com.mysql.jdbc.Util.getInstance(Util.java:381)
      at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
      at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
      at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
      at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
      at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
      at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
      at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536)
      at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1564)
      at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1485)
      at BaseDatosSetup.BaseDatosSetup.main(BaseDatosSetup.java:18)
  </code></pre>
  
  <p>I solved it by granting the create action to the user. I don't know why, I was doing it as an administrator.</p>