从mysql网站检索时没有选择数据库

Joe*_*eyL 3 java mysql

我有一个mysql数据库,我试图从我们的网站主机(godaddy)检索.我遵循了一个似乎正确的格式,但它告诉我:

java.sql.SQLException: No database selected
Run Code Online (Sandbox Code Playgroud)

码:

public static void main(String[] args) {

    Connection conn = null;
    Statement stmt = null;

    try {
        // STEP 2: Register JDBC driver
        Class.forName(JDBC_DRIVER);

        // STEP 3: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        // STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        String sql;
        sql = "SELECT * FROM item_master";
        ResultSet rs = stmt.executeQuery(sql);  //<-- This is where the error is.

        // STEP 5: Extract data from result set
        while (rs.next()) {
            // Retrieve by column name
            int id = rs.getInt("id");

            // Display values
            System.out.print("ID: " + id);
        }
...
}
Run Code Online (Sandbox Code Playgroud)

我做了conn的打印声明,可能认为连接可能是null并且显示如下:

com.mysql.jdbc.JDBC4Connection@2a6*****
Run Code Online (Sandbox Code Playgroud)

任何人有什么想法会导致这样的事情?

Stu*_*yte 11

您的数据库URL应包含您的数据库名称.这通常是您的URL后跟"/ DBNAME".

String URL = "jdbc:mysql://localhost:3306/mydb";

"mydb"是您的数据库名称.