无法使用java成功连接到mysql数据库

时间:2016-04-08 00:54:39

标签: java mysql

所以这个数据库的目的是执行将访问它的网站所需的查询,这里是代码:

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

public class Connect_Database {
 // JDBC driver name and database URL
 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
 static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/?user=root";

 //  Database credentials
 static final String USER = "root";
 static final String PASS = ;

 public static void main(String[] args) {
 Connection conn = null;
 Statement stmt = null;
 try{
    //STEP 2: Register JDBC driver
   Class.forName("com.mysql.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 = "INSERT INTO Inventory " + "VALUES (shirt,1234,5)";
    stmt.executeUpdate(sql);


 }catch(SQLException se){
    //Handle errors for JDBC
    se.printStackTrace();
 }catch(Exception e){
//Handle errors for Class.forName
    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

}
 }

这是错误:

java.sql.SQLException: No database selected
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1600)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1695)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3020)
    at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1074)
    at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1008)
    at dodRus.Connect_Database.main(Connect_Database.java:30)

显然它没有成功连接到数据库,但我无法弄清楚为什么

1 个答案:

答案 0 :(得分:2)

您需要在DSN字符串中包含数据库名称。

static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/<name_of_database>?user=" + USER + "&password=" + PASS;

请参阅Connector/J documentation