在Java中连接到MySQL数据库时访问被拒绝

时间:2013-08-12 12:35:22

标签: java mysql database eclipse xampp

我正在使用mysql数据库作为存储构建我自己的CRM(客户关系管理器)应用程序,我现在正在尝试将我的Eclipse Java项目链接到数据库,以便表格变得可见。 我正在尝试运行此代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//import java.util.Date;

public class MySQLclass{
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;

public void readDataBase() throws Exception {
try {
  // This will load the MySQL driver, each DB has its own driver
  Class.forName("com.mysql.jdbc.Driver");
  // Setup the connection with the DB
  connect = DriverManager
      .getConnection("jdbc:mysql://localhost/test"
          + "user=root&password=password");

  // Statements allow to issue SQL queries to the database
  statement = connect.createStatement();
  // Result set get the result of the SQL query
  resultSet = statement
      .executeQuery("select * from test.customers");
  writeResultSet(resultSet);

  // PreparedStatements can use variables and are more efficient
  preparedStatement = connect
      .prepareStatement("insert into  test.customers values (default, ?, ?, ?, ? , ?,        ?, ?)");
  // "myuser, webpage, datum, summary, customers from test.customers");
  // Parameters start with 1
  preparedStatement.setString(1, "Sjaakie Sjaakssen");
  preparedStatement.setString(2, "Sjaakssen@yahoo.nl");
  preparedStatement.setString(3, "pannekoekenstraat 2");
  preparedStatement.setString(4, "Rotterdam");
  preparedStatement.setString(5, "3022PK");
  preparedStatement.setString(6, "0101235489");
  preparedStatement.setString(7, "Yahoo");
  preparedStatement.executeUpdate();

  preparedStatement = connect
      .prepareStatement("SELECT NAAM, EMAIL, TELEFOON, BEDRIJFSNAAM, customers from test.customers");    
  resultSet = preparedStatement.executeQuery();
  writeResultSet(resultSet);

  // Remove again the insert comment
  preparedStatement = connect
  .prepareStatement("delete from test.customers where NAAM= ? ; ");
  preparedStatement.setString(1, "Test");
  preparedStatement.executeUpdate();

  resultSet = statement
  .executeQuery("select * from test.customers");
  writeMetaData(resultSet);

} catch (Exception e) {
  throw e;
} finally {
  close();
}

}

private void writeMetaData(ResultSet resultSet) throws SQLException {
//   Now get some metadata from the database
// Result set get the result of the SQL query

System.out.println("The columns in the table are: ");

System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
for  (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
  System.out.println("Column " +i  + " "+ resultSet.getMetaData().getColumnName(i));
 }
}

private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
  // It is possible to get the columns via name
  // also possible to get the columns via the column number
  // which starts at 1
  // e.g. resultSet.getSTring(2);
  String Naam = resultSet.getString("naam");
  String Email = resultSet.getString("email");
  String Adres = resultSet.getString("adres");
  String plaats = resultSet.getString("plaats");
  String Postcode = resultSet.getString("postcode");
  String Telefoon = resultSet.getString("telefoon");
  String Bedrijfsnaam = resultSet.getString("bedrijfsnaam");
  System.out.println("Naam: " + Naam);
  System.out.println("Email: " + Email);
  System.out.println("Adres: " + Adres);
  System.out.println("plaats: " + plaats);
  System.out.println("Postcode: " + Postcode);
  System.out.println("Telefoon:" + Telefoon);
  System.out.println("Bedrijfsnaam" + Bedrijfsnaam);
  }
    }

     // You need to close the resultSet
 private void close() {
    try {
      if (resultSet != null) {
        resultSet.close();
      }

      if (statement != null) {
        statement.close();
      }

      if (connect != null) {
    connect.close();
      }
    } catch (Exception e) {

    }
  }

} 

有这个主要类:

public class Main {
  public static void main(String[] args) throws Exception {
    MySQLclass dao = new MySQLclass();
dao.readDataBase();
  }


} 

我一直收到这个错误:

Exception in thread "main" java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4187)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4119)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:927)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1709)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1252)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2483)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2516)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2301)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at MySQLclass.readDataBase(MySQLclass.java:22)
at Main.main(Main.java:5)

有人可以解释一下我的困境。

3 个答案:

答案 0 :(得分:4)

线索出现错误:

Access denied for user ''@'localhost'

它认为用户名是''(空字符串) 在数据库URL中,您忘记将URL中的路径与带有问号的参数分开。

试试这个:

connect = DriverManager
  .getConnection("jdbc:mysql://localhost/test?"
      + "user=root&password=MSQLpass21!");

答案 1 :(得分:0)

您可以使用public static Connection getConnection(String url, String user, String password)来获取使用用户名和密码的连接 或者尝试connect = DriverManager.getConnection("jdbc:mysql://localhost/test?" + "user=root&password=MSQLpass21!");

答案 2 :(得分:0)

您的第二个错误可能是由此行引起的:

SELECT NAAM, EMAIL, TELEFOON, BEDRIJFSNAAM, customers from test.customers

如果customers是表名,则不能在select子句中使用它。使用select *或使用您要获取的所有特定字段名称:

SELECT NAAM, EMAIL, TELEFOON, BEDRIJFSNAAM from test.customers