Trouble creating a database in MySQL using java

Hi all,
I am trying to create a program that connects to MySQL and can create databases, tables etc. I can connect to MySQL using the program but I cannot create a database (however if i create the database with the command line i can create tables in the database).
When I try to create a database i get the error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'persondatabase'Here is the code:
import java.sql.*;
class Connect {
public Connect() {
public Connection connectToMySQL(String database_name) {
  Connection con = null;
  try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   con = DriverManager.getConnection("jdbc:mysql:///persondatabase", "", "");
  catch(ClassNotFoundException e) { System.out.println(e); }
  catch(InstantiationException e) { System.out.println(e); }
  catch(SQLException e) { System.out.println(e); }
  finally {
   return con;
public void createDatabase(String database_name) {
  Connection con = null;
  Statement stmt = null;
  try {
   con = connectToMySQL(null);  //connect to mysql but not to any one databases
   con.setAutoCommit(false);
   if(!con.isClosed())
    System.out.println("Connected to MySQL. Creating the Database " + database_name);
   String str = "CREATE DATABASE " + database_name;
   stmt = con.createStatement();
   stmt.executeUpdate(str);
   con.commit();
  catch (Exception e2) { }
  finally {
   try {
    stmt.close();
    con.close();
   }catch (Exception e3) { }
public void createPersonDetailsTable(String database_name, String table_name) {
  Connection con = null;
  Statement stmt = null;
  try {
   con = connectToMySQL(database_name);
   con.setAutoCommit(false);
   if(!con.isClosed())
    System.out.println("Connected to " + database_name + " creating the table " + table_name);
   String str = "CREATE TABLE " + table_name + "(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(25), last_name VARCHAR(25), address VARCHAR(40), suburb VARCHAR(20), state VARCHAR(3), post_code INT(1), contact_number INT(10), email_address VARCHAR(40));";
   stmt = con.createStatement();
   stmt.executeUpdate(str);
   con.commit();
  catch (Exception e2) { System.out.println(e2); }
  finally {
   try {
    stmt.close();
    con.close();
   }catch (Exception e3) {  }
}I am wondering if anyone can see where im going wrong? I am currently connecting with an anon account to MySQL.
Here is the program I am using to test the above:
class ConnectionTester {
public ConnectionTester() {
  Connect s = new Connect();
  s.createDatabase("PersonDatabase");  //this throws the error
  //s.createPersonDetailsTable("PersonDatabase", "PersonDetails");
public static void main(String[] arg) {
  ConnectionTester start = new ConnectionTester();
}

you should rethink whether you need to create a database using java. personally i think it's a bad idea. your database should exist and the schema should be ready to go when your app starts. why do you think you need to create one?
%

Similar Messages

  • How to convert oracle 9i database to mysql using JSP?

    Dear friends,
    I want to convert oracle 9i database to mysql using JSP technology. Does there anyone who have a hint or some web links about this task? I searched the internet and found all of them are not free and no source code. In fact, what I want to do is really simple, I just want to first, reading the oracle database table structure information and then create the exactly same table in mysql, and then copying all the data in oracle database table to mysql table. But I don�t know how to retrieve the oracle table structure using JDBC. And also I want to retrieve all the tables in the oracle database, so I can choose from them to convert to mysql. It seems that the structure in oracle usually have the tablespace information, I don�t know if I can create database in mysql using this tablespace information. And I don�t know where I can find the information about the functions in JDBC? For example, how to retrieve the table structure? Once I retrieve the table structure and create the exactly same table structure in mysql, then I can fetch all the data in oracle table to mysql table.
    Any hint will be great appreciated!
    Merry Christmas and Happy new year!
    Sammy

    Hi, beattris and rtg54,
    thank you very much for your great help!
    beattris, do you know if there is any such kind of tool free? I am a student and don't want to do commercial product, as you see, my work is very simple, in fact, just as you said, the most important of all is how to get the database structure from oracle schema? do you have any idea about this? or do you know any tool that is open source? so I can learn from it.
    rtg54, I just want to convert the database from oracle to mysql, after that, I can use mysql database as storage instead of expensive oracle database. the problem is that I have some data stored in oracle database and the application is built on oracle, after the convertion, I can use mysql to provide data to jsp or servlet application. I will great appreciate if you can contact with mysql about this problem because I don't know how to contact with them.
    thanks again and happy new year!
    Sammy

  • Create a database from scratch using php.

    Is it possible to create the usernames and databases for
    mysql using a php script, or can this only be done using
    phpmyadmin.
    if it can how.
    thanks

    Sure, you should be able to execute ddl command from a php
    script. Why do you want to?

  • How to create the groups in OID Using Java API.

    Hi,
    I need to create the group in OID Using Java API's only(i.e., javax.naming.* only).
    I need to achieve it without using any oracle specific jars.
    Is there any way to achieve it?.If there's a option to achieve it,do let me know.
    I also need to create the users in that group ,after creating it.
    If you share any useful link or ideas for the same would be great.
    Thanks
    Balaji

    bobws wrote:
    Hi,
    I want to find the installed JREs in windows using java. I couldn't fine any java API. So I am using the below code to fetch the JRE list from windows registries & parse the returned collection to know the installed JRE.Why? If you are running java you already have a JRE. So why not just use it?
    >
    String key = "HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment";
    Runtime.getRuntime().exec(
    "reg query " + "\"" + key + "\"");
    Is it legal to retrieve the installed JREs in this way? Legal? It is OS specific, and to a certain extent dependent on vendor and what the vendor wants to do. Could also be impacted by permissions. Other than that it is ok.
    I am feeling like its a type of hacking. So I couldn't decide whether this is legal (recommended) way of using. Does anybody can answer me. I can see the similar posts in google. Somebody suggests this way & somebody suggests to use preference API which is similar to this. Appreciate your help.Preferences won't work. It doesn't allow access to the registry in general, only a part of it. There are discussions in the JNI forum about retrieving VM versions. Prior to actually using the VM though.

  • How to create a ms-access database at runtime using java

    hi, this is ravi kiran,
    i have a situation where i need to create a new ms-access database with one table in it at runtime(when user clicks on some button).
    i have been searching many sites to know how to do this in java, but i didnot find any thing useful.
    plz tell me how to do this in java.
    plz help me, its urgent
    thanx in advance.

    Here's how I did it. Research does help, but sometimes looking at others code does too... You do have to have a dummy file that you made with access though. You can't just make a file file.mdb (it will be corrupt)
         public void createDatabase(String database) throws SQLException{
              try{
                   // This file needs to have been created with MS Access
                   File dbfile = new File(this.dataBaseDir + "dummy.mdb");
                   // This is the new database file being made
                   File newFile = new File(this.dataBaseDir + database + ".mdb");
                   // Copy all bytes from dummy file to new DB file.
                   FileInputStream instream = new FileInputStream(dbfile);
                   FileOutputStream ostream = new FileOutputStream(newFile);
                   int numBytes = instream.available();
                   byte inBytes[] = new byte[numBytes];
                   instream.read(inBytes, 0, numBytes);
                   ostream.write(inBytes, 0, numBytes);
              catch(FileNotFoundException e) { e.printStackTrace();}
              catch(IOException e) { e.printStackTrace();}
              if(DEBUG) System.out.println("creating the " + database + " database");
         }

  • How to create hyperlink in Html page using Java

    Hello every one
    I want to know that how can I create a hyperlink in Html page using java ?
    Let for example
    I have code like this and i want to give hyperlink to it using java.
    rember that i am creating node using this id="name" which give me multiple value. and i want to assign diff link to each name..?
    <tr>
    <td ><span id="name"></span>
    </tr>

    but i m using this code to create node in html file
    HTMLLIElement li = (HTMLLIElement)appHTML.createElement("LI");
    Text txt = appHTML.createTextNode(name);
    li.appendChild(txt);
    appHTML.getElementById("name").appendChild(li);
    this will display all name value which is coming from database,
    and i want to assign a hyperlink to it,
    I have id with name also so I thought that using id i will
    create javascript like
    function popup(id)
         if(id==1)
              var n1 = window.open("../list/name1.html");
         if(id==2)
              var n1 = window.open("../list/name2.html");
    this way i want to popup particular file if i can pass id value in this function
    so want hyperlink like
    name

  • How create new database and table in java db and how get java db backup

    hi master
    sir i use stuido creator
    sir please give me idea how i create new database
    and how create new table and view in this new database
    and how get this database backup
    how i give this databae backup to isp for deployment
    please give me idea with step
    thank
    aamir

    Create your own Value Object (Data Transfer Object) in Java with a structure similar to this and map the fields returned from the database to the fields of that object (preferably using SEtT methods).
    Hope this helps.

  • Creating OO database objects by using class diagrams in JDeveloper

    I am new to use JDeveloper. I create UML class diagrams (using Entity Object) in JDeveloper, which has inheritances and associations, and then choose Create Database Objects... try to create oo database, but it only create some tables in the database, not any object types ... .
    What do I missed? Or I have to create those oo database objects manually?
    Thanks.

    Tony,
    You can use database object types with BC4J, but only to implement BC4J domains (these can map to object types).
    For performance reasons, it is less practical to generate a table of object types for a complete EO. Most users view the BC4J layer as the 'pure' OO model, and map to a relational datamodel for optimal performance.
    Below some steps to create a DB object type for a domain:
    You can create Oracle Object Types in the database by creating a business component domain and then forward generating the database object. Forward generation of object tables from entity objects is not supported. To forward generate an Oracle Object Type from a new domain: In the System Navigator, right click on your business component package and choose Create Domain. When the Domain Wizard opens, review the information on the Welcome page and click Next. Enter a Name and Package for the domain or accept the defaults. Select the checkbox for Domain for an Oracle Object Type. Do not select any items on the Available Types list, as you are creating a new one. Enter the name of your new type in the Selected Type field. Click Next. On the Settings page, click New. Provide a name in the New Domain Attribute box. Select the appropriate Java type a[i]Long postings are being truncated to ~1 kB at this time.

  • How to create  and hide a drive using java?

    I want to ask how to create a temporary drive/ or a drive by allocating some space of existing drives(eg allocating some space of C: Drive such as 5mb for storing files on the new drive that has been created) and then i want to hide that drive .So Please can anyone Explain me how to do that.

    Iam saying to all of you iam not blaming to anyone even java. And my harddisk is not currepted or damage by using that. My harddisk is working properly. But i don't know why all of you think that i am blamming to someone but iam asking some question which need to be answered.
    I am clearing all of you i am a student and iam creating an project in java for that i need this. I also want to add File/Folder lock on that project. This technique i have seen in folder lock 6 software that they use hidden drive to store files. Thats why iam asking that how to apply this technique using java.
    And plz plz read this carefully and answer me to solve my problem.

  • How to create a directory or Folder  using java program?

    Hi all,
    Can any one know, how to create a directory(new folder) in java.
    can any give me some idea, on creating a directory using java program dynamically.
    thanx in advance

    hi thanks for your answer,
    sorry, actual i know this technique(its my fault i didnt mentioned it)
    i am looking for some what different technique.
    bye
    ram

  • Problem of accesing MS Acess database on Linux using Java

    Below is my java code and errors found. Can anyone guide me tell me what is the problem and how to success access the .mdb file using Java on Linux?
    import java.sql.*;
    class readmdb
    {      public static void main(String[] args)
    {    String url;
    Connection con;
    Statement stmt;
    try
    {     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    catch(java.lang.ClassNotFoundException e)
    {    System.out.print("ClassNotFoundException: ");
    System.out.println(e.getMessage());
    try
    {     con = DriverManager.getConnection("jdbc:odbc:DRIVER={/usr/local/lib/libmdbodbc.o.O}};DBQ=/home/powerstation/db/Database.mdb");
    stmt = con.createStatement();
    stmt.close();
    con.close();
    catch(SQLException ex)
    { System.err.println("SQLException: " + ex.getMessage());
    Errors messages found after i executed the java code
    shown above on linux platform.
    Exception in thread "main"
    java.lang.NullPointerException
    at sun.jdbc.odbc.JdbcOdbcDriver.initialize(JdbcOdbcDriver.java:436)
    at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:153)
    at java.sql.DriverManager.getConnection(DriverManager.java:512)
    atjava.sql.DriverManager.getConnection(DriverManager.java:193)
    at readmdb.main(readmdb.java:27)

    jschell,
    ODBC shell is the odbc.ini or odbcinst.ini? No.
    The shell is something that you explicitly installed. Just like you installed Apache, or perl, or a C++ compiler, or even a CD driver.
    If yes,
    What is the difference between odbc.in and
    odbcinst.ini? No idea. But on a windows box those are ini files that specify odbc info. I don't think ini files are going to help on linux.
    Which of them will be execute when i
    want to establish a connection using "jdbc:odbc:...."
    in DriverManager.getConnection?I am rather sure that neither of them would 'execute'
    >
    Is it MS Access ODBC linux driver is the file like
    libodbc.so, libmdbodbc.so, libmdbsql.so and so on?No idea, but I doubt it.
    What makes you think that you even have a MS Access ODBC linux driver on your box?
    Then, can u tell me which is MS Access ODBC linux
    driver or what is the driver file name for MS Access
    ODBC linux driver?Nope.
    If you installed a MS Access ODBC linux driver, then the ODBC shell will know where it is.
    And if you did install such a driver you should post the link where you got it here, because as far as I know, there is no such driver (nor is there one for MS SQL Server.)

  • Creating a user defined control using java Beans

    Hi,
    I want to create a user defined control which is used to draw a line ...
    same as we using in VB as Line control.In java we will create the component using using Beans . I created a code
    which will draw a line in the run time .For tat i extend the class with JPanel,but i cant use the same program in beans....b'coz it simply draws the jpanel when we drag and drop that control in the form....
    so can u give me some ideas to create a control which is used to draw a line .....i am attaching the same which i did .....
    thank u in advance...
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Line extends JPanel
    BufferedImage image;
    Color color;
    Stroke stroke;
    Point start = new Point();
    Point end = new Point();
    public Line()
    color = Color.blue;
    stroke = new BasicStroke(1f, BasicStroke.CAP_BUTT,
    BasicStroke.JOIN_MITER);
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    if(image == null)
    initImage();
    g.drawImage(image, 0, 0, this);
    // Draw temp line over image.
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setPaint(Color.red);
    g2.drawLine(start.x, start.y, end.x, end.y);
    public void setTempPoints(Point p1, Point p2) {
    start = p1;
    end = p2;
    repaint();
    public void draw(Point p1, Point p2)
    Graphics2D g2 = image.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setPaint(color);
    g2.setStroke(stroke);
    g2.drawLine(p1.x, p1.y, p2.x, p2.y);
    g2.dispose();
    start = end;
    repaint();
    private void clearImage()
    Graphics g = image.getGraphics();
    g.setColor(getBackground());
    g.fillRect(0, 0, image.getWidth(), image.getHeight());
    g.dispose();
    repaint();
    private void initImage()
    int w = getWidth();
    int h = getHeight();
    image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.setPaint(getBackground());
    g2.fillRect(0,0,w,h);
    g2.dispose();
    public static void main(String[] args)
    Line wbclient = new Line();
    DrawingListener listener = new DrawingListener(wbclient);
    wbclient.addMouseListener(listener);
    wbclient.addMouseMotionListener(listener);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(wbclient);
    f.setSize(400,400);
    f.setLocation(200,200);
    f.setVisible(true);
    class DrawingListener extends MouseInputAdapter
    Line wbclient;
    Point start;
    Point end;
    final int MIN_DIST = 5;
    public DrawingListener(Line fh)
    this.wbclient = fh;
    public void mousePressed(MouseEvent e)
    start = e.getPoint();
    public void mouseReleased(MouseEvent e)
    end=e.getPoint();
    if(start.distance(end) > MIN_DIST)
    wbclient.draw(start, end);
    public void mouseDragged(MouseEvent e)
    wbclient.setTempPoints(start, e.getPoint());
    }

    Hi Ravi,
    How about something like this:
    IUserMaint user = UMFactory.getUserFactory().newUser("myNewUser");
    user.setFirstName("1st Name");
    user.setLastName("2nd Name");
    user.setEmail("[email protected]");
    user.save();
    user.commit();
    IUserAccount uacc = UMFactory.getUserAccountFactory().newUserAccount("myNewUser", user.getUniqueID());
    uacc.setPassword("initial");
    uacc.setPasswordChangeRequired(false);
    uacc.save();
    uacc.commit();
    Hope this helps.
    Daniel

  • ORA-12523 while creating a database on ASM using DBCA

    HI PPL,
    I have set up am ASM instance and also configured the listener services to it.
    But when I try to create database on the configured ASM instance using DBCA , I am getting the following error
    TNS:listener could not find instance appropriate
    for the client connection
    The Connection descriptor used by the client was:
    (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP(Host=10.10.199.141)
    (Port=6881))(CONNECT_DATA=(SERVICE_NAME++ASM1)
    (INSTANCE_NAME=+ASM1)(UR=A)))
    I have checked the listener status and ASM instance and booth seem to be fine:
    $ lsnrctl status ASM
    LSNRCTL for HPUX: Version 10.2.0.3.0 - Production on 30-JUL-2010 12:40:17
    Copyright (c) 1991, 2006, Oracle. All rights reserved.
    Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.10.199.141)(PORT=6881)))
    STATUS of the LISTENER
    Alias ASM
    Version TNSLSNR for HPUX: Version 10.2.0.3.0 - Production
    Start Date 30-JUL-2010 11:36:11
    Uptime 0 days 1 hr. 4 min. 5 sec
    Trace Level off
    Security ON: Local OS Authentication
    SNMP OFF
    Listener Parameter File /uat06/asm_home/network/admin/listener.ora
    Listener Log File /uat06/asm_home/network/log/asm.log
    Listening Endpoints Summary...
    (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.10.199.141)(PORT=6881)))
    Services Summary...
    Service "+ASM" has 1 instance(s).
    Instance "ASM", status BLOCKED, has 1 handler(s) for this service...
    Service "+ASM_XPT" has 1 instance(s).
    Instance "ASM", status BLOCKED, has 1 handler(s) for this service...
    Service "ASM" has 1 instance(s).
    Instance "ASM", status UNKNOWN, has 1 handler(s) for this service...
    Service "PLSExtProc" has 1 instance(s).
    Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
    The command completed successfully
    SQL> sho parameter local
    NAME TYPE VALUE
    local_listener string ASM
    log_archive_local_first boolean TRUE
    Please help as I am new to ASM.
    OS-HP-UX
    Database;10gR2
    regards

    HI Chinar,
    I have already checke the same and made the changes as per the metalink note.
    But stil I am getting teh following error:
    $ lsnrctl status ASM
    LSNRCTL for HPUX: Version 10.2.0.3.0 - Production on 30-JUL-2010 12:40:17
    Copyright (c) 1991, 2006, Oracle. All rights reserved.
    Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.10.199.141)(PORT=6881)))
    STATUS of the LISTENER
    Alias ASM
    Version TNSLSNR for HPUX: Version 10.2.0.3.0 - Production
    Start Date 30-JUL-2010 11:36:11
    Uptime 0 days 1 hr. 4 min. 5 sec
    Trace Level off
    Security ON: Local OS Authentication
    SNMP OFF
    Listener Parameter File /uat06/asm_home/network/admin/listener.ora
    Listener Log File /uat06/asm_home/network/log/asm.log
    Listening Endpoints Summary...
    (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.10.199.141)(PORT=6881)))
    Services Summary...
    Service "+ASM" has 1 instance(s).
    Instance "ASM", status BLOCKED, has 1 handler(s) for this service...
    Service "+ASM_XPT" has 1 instance(s).
    Instance "ASM", status BLOCKED, has 1 handler(s) for this service...
    Service "ASM" has 1 instance(s).
    Instance "ASM", status UNKNOWN, has 1 handler(s) for this service...
    Service "PLSExtProc" has 1 instance(s).
    Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
    The command completed successfully
    Why is it showing status "BLOCKED" if i check the listener status.

  • How to retrieve the data stored in BLOB field in MySql using java?

    Hi all!
    i stored a file content into the MySql database in BLOB field.
    and i now want retrieve the data......
    Please help me out in doing the task...........
    Thanx...........

    Thrisha..
    When u get a result set u can have rs.getBlob() function that will give u a BLOB object that can be captured using Blob interface of javax.sql package...
    Blob interface has getBinaryStream, getBytes etc as functions...
    i think i cleared u
    regards
    Shanu

  • Database access design using java bean

    Hi,
    I am writing a JSP/servlet/Javabean based app. using MVC architecture.The database related logic is in java beans.
    I want a generalized class/bean that can form a connection , execute the passed query and return the results.Does any one has any URLs or sample code to explain how to do this using introspection?
    I would greatly appreciate any help as this design is very crucial for our application.
    Thanks -
    k

    Please check the Cameleon Open Source project at http://www.must.de/cameleon.html if ti fits your needs.

Maybe you are looking for

  • How can I retrieve password in order to download updates?

    We receive many messages with updates for the computer, especially for new iphone in order to use itunes. Neither of us remembers the password.  Any way to retrieve it?

  • Photoshop Album 2 unlock code

    I have photoshop 2 starter edition. I have the unlock code. But it tells me I have to administrator rights in order to do this. I use Win ME and I am the only user it's not set up for administrator or any other user. What do I do???? I really like th

  • Does Apple Mail have a "return receipt" feature similar to Outlook?

    Does Apple Mail have a "return receipt" feature similar to Outlook?

  • Merge with Multi users

    Hi, We want to insert data in Inventory table if item does not exist, if it exists, update the item. We plan to use the MERGE statement, and want to confirm if this will work fine if multiple users use this functionality simultaneously. If not, then

  • Disable the "enter a password to unlock the disk" prompt

    is there a way to disable the "enter a password to unlock the disk" prompt? My macbook has 2 logical drives, one of them is encrypted, and everytime I start the Mac os x it pops up with that prompt. Any help is appreciated!