Databases selected when fetching from mysql site

I have a mysql database that I am trying to get from our site host (godaddy). I followed the format, which seems to be correct, but it tells me that:

java.sql.SQLException: No database selected

      

code:

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);
        }
...
}

      

I made a print statement for conn to think that the connection might be null and it showed this:

com.mysql.jdbc.JDBC4Connection@2a6*****

      

Anyone have any ideas what might be causing something like this?

+3


source to share


3 answers


Your url for your database should contain the name of your database. This is usually your URL followed by "/ DBNAME".

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



Where "mydb" is your database name.

+11


source


What is the value of DB_URL? As far as I know, the url should be of the form: "WEBURL / DATABASENAME: PORT" Are you just trying to connect to WEBURL without specifying a database?



+1


source


I had the same problem.

Just run another query (before the SELECT statement) to connect to your database.

Firstly:

sql = "USE <yourdatabase>";

ResultSet rs = stmt.executeQuery(sql); 

      

And after:

sql = "SELECT * FROM item_master";

rs = stmt.executeQuery(sql);

      

0


source







All Articles