有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JDBC未选择任何数据库

我的java类中有以下代码,但我无法创建单个表,因为它不会选择数据库

//STEP 1. Import required packages
import java.sql.*;

public class DBTest {
    // Database credentials
    private static final String USER = "root";
    private static final String PASS = "1234";

    private static Connection conn = null;
    private static Statement stmt = null;

    static final String DB_URL = "jdbc:mysql://localhost/";

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        getConnection();
    }

    public static Connection getConnection() throws SQLException, ClassNotFoundException {

        try {
            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            createTable(conn);

        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // finally block used to close resources
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException se2) {
            } // nothing we can do
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            } // end finally try
        } // end try
        return conn;
    }

    public static void createTable(Connection conn) throws SQLException {
        System.out.println("Creating database...");
        stmt = conn.createStatement();

        // Open a connection
        System.out.println("Connecting to a selected database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        System.out.println("Connected database successfully...");

        // Execute a query
        System.out.println("Creating table in given database...");

        String sql = "CREATE TABLE REGISTRATION " + "(id INTEGER not NULL, " + " first VARCHAR(255), "
                + " last VARCHAR(255), " + " age INTEGER, " + " PRIMARY KEY ( id ))";

        stmt.executeUpdate(sql);
        System.out.println("Created table in given database...");
    }

}

请注意:我导入的唯一库是java。sql,我已经在引用库中设置了连接器,所以应该设置所有内容! enter image description here

考虑到所有这些,有人能告诉我为什么选择了无数据库SQLException吗


共 (2) 个答案

  1. # 1 楼答案

    在您的数据库中,DB_URL变量缺少数据库名称:

    你只需要:

    jdbc:mysql://localhost/my_db_name

    其中my_db_name是您创建的数据库的名称

  2. # 2 楼答案

    只有连接到数据库时才能创建表。目前,您只连接到服务器,所以像CREATE TABLE这样的语句无法执行,因为没有任何东西可以在其中创建该表

    您需要在连接字符串中指定数据库:

    jdbc:mysql://localhost/<database>
    

    或者,您需要明确地使用以下命令切换到数据库:

    connection.setCatalog("<database>");
    

    从评论来看,你真正的问题似乎是如何从java创建一个新的数据库,要回答这个问题,你需要看看:Create MySQL database from Java