使用 Java 连接到 MySQL 数据库时拒绝访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18187155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access Denied when connecting to MySQL database in Java
提问by user2674895
I am building my own CRM(Customer Relationship Manager) application using a mysql database as storage, I now am trying to link my Eclipse Java project to the database so the tables become visible. I'm trying to run this code:
我正在使用 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, "[email protected]");
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) {
}
}
}
with this main class:
使用这个主类:
public class Main {
public static void main(String[] args) throws Exception {
MySQLclass dao = new MySQLclass();
dao.readDataBase();
}
}
And i keep getting this error:
我不断收到此错误:
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)
Could someone please shed some light on my dilemma.
有人可以对我的困境有所了解。
采纳答案by c.s.
Your second error is probably caused by this line:
您的第二个错误可能是由这一行引起的:
SELECT NAAM, EMAIL, TELEFOON, BEDRIJFSNAAM, customers from test.customers
if customers
is a table name you cannot use it in the select clause. Either use select *
or use all the specific field names you want to fetch:
如果customers
是表名,则不能在 select 子句中使用它。使用select *
或使用您要获取的所有特定字段名称:
SELECT NAAM, EMAIL, TELEFOON, BEDRIJFSNAAM from test.customers
回答by NickJ
The clue is in the error:
线索在错误中:
Access denied for user ''@'localhost'
It thinks the username is '' (empty string) In the database URL, you forgot to separate the path in the URL from the parameters with a question mark.
它认为用户名是 '' (空字符串) 在数据库 URL 中,您忘记用问号将 URL 中的路径与参数分开。
Try this:
尝试这个:
connect = DriverManager
.getConnection("jdbc:mysql://localhost/test?"
+ "user=root&password=MSQLpass21!");
回答by venkat balabhadra
You could use public static Connection getConnection(String url, String user, String password)
to get connection using user name and password.
Or try out connect = DriverManager.getConnection("jdbc:mysql://localhost/test?"
+ "user=root&password=MSQLpass21!");
您可以使用public static Connection getConnection(String url, String user, String password)
用户名和密码来获取连接。
或者试试connect = DriverManager.getConnection("jdbc:mysql://localhost/test?"
+ "user=root&password=MSQLpass21!");