使用Java创建并连接到SQL数据库

乔恩·奥多德

我有一个连接到SQL数据库的Java程序,可以从其中进行读写操作,但是,要使用该程序,我首先必须打开Workbench,然后在其中运行SQL查询。

显然,这不是一个很好的解决方案,那么如何在Java代码中创建和连接数据库呢?

我已经在线搜索过,包括Oracle网站,但看不到它。

下面是我的代码。

public Connection ConnectNow() //Connect to the database
{
    try 
    {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } 

    catch (Exception ex) 
    {
        System.out.println("Error 1");
        ex.getMessage();
    }

    final String dbURL = "jdbc:mysql://localhost/game1"; //replace 'assignex' with database name
    Connection conn = null;

    try 
    {
        conn = DriverManager.getConnection(dbURL, "root", "password");

        System.out.println("\n== Connection Successful ==");

        return conn;
    } 

    catch (SQLException ex) 
    {
        System.out.println("Error 2");
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());

        return null;
    }
}


public void CreateDatabase()
{
    try
    {
        Connection conn = ConnectNow();
        Statement stmt = conn.createStatement();

        String createDatabase = "CREATE DATABASE IF NOT EXISTS game1"; //creates database
        stmt.executeUpdate(createDatabase);

        conn.close();
        stmt.close();

        System.out.println("<< Database created successfully >>");
    }

    catch (Exception ex)
    {
        System.out.println("Error 7");
        ex.getMessage();
        ex.printStackTrace();
    }
}

public void CreateTable() //creates a table within the database
{
    try
    {
        Connection conn = ConnectNow();
        Statement stmt = conn.createStatement();

        String createTable = "CREATE TABLE IF NOT EXISTS user" + 
                             "(firstname VARCHAR(255), " + //AUTO_INCREMENT to add numbers automatically
                             " surname VARCHAR(255), " +
                             " day INTEGER, " +
                             " month INTEGER, " +
                             " year INTEGER, " +
                             " username VARCHAR(255) NOT NULL, " +
                             " password VARCHAR(255), " +
                             " PRIMARY KEY (username))";
        stmt.executeUpdate(createTable);

        conn.close();
        stmt.close();

        System.out.println("<< Table created successfully >>");
    }

    catch (Exception ex)
    {
        System.out.println("Error 6");
        ex.getMessage();
        ex.printStackTrace();
    }
}

大概与我尝试在创建数据库之前进行连接有关,但是我找不到正确实现此方案的解决方案。

非常感谢您的帮助。

布莱恩·C

您已经回答了自己的问题。您的连接URL(jdbc:mysql:// localhost / game1)指定要连接的数据库(game1),但该数据库不存在。如果您查看您的Exception输出,则可能恰好说明了这一点。您的应用程序不应创建数据库。它应该只是连接到它并对其进行修改。您可以尝试将URL设置为不包含数据库名称,然后仅使用MySQL USE命令指定数据库,但这是许多不必要的工作。只是没有应用程序创建它的数据库。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章