这是我的代码:
import java.sql.*;
import com.mysql.jdbc.Statement;
public class Test {
public static void main(String[] args) throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Something happened badly");
e.printStackTrace();
}
final String DB_URL = "jdbc:mysql://localhost/";
final String USER = "root";
final String PASSWORD = "XXXXX";
Connection conn = DriverManager.getConnection(DB_URL,USER,PASSWORD);
//String db = "CREATE DATABASE TEST1";
String use_db = "USE football_manager";
Statement stmt;
String createTable = "CREATE TABLE coffees "
+ "(COF_NAME VARCHAR(30),"
+ "SUPPLIER VARCHAR(30),"
+ "PRICE FLOAT,"
+ "STOCK INTEGER)";
try {
conn = DriverManager.getConnection(DB_URL);
//stmt = (Statement) conn.createStatement();
// stmt.executeUpdate(db);
stmt = (Statement) conn.createStatement();
stmt.executeUpdate(use_db);
stmt = (Statement) conn.createStatement();
stmt.executeUpdate(createTable);
stmt.close();
conn.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
以下是我在控制台中收到的消息:
SQLException:用户访问被拒绝'' localhost'到数据库
如您所见,用户名已留空。我正在使用Eclipse Luna。当我使用Eclipse Kepler时,这很好用。
答案 0 :(得分:2)
你的问题在这里:
conn = DriverManager.getConnection(DB_URL);
您正在获取第二个连接对象但未发送用户凭据。我不确定你为什么要/需要打开第二个连接,使用第一个连接。