我无法使用Eclipse连接到mySQL,无法找出原因。
这是我的连接类:
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class ConnexionBDD {
static String url = "jdbc:mysql://localhost:8888/Peoples?autoReconnect=true&useSSL=false";
static String login = "root";
static String password = "";
static Connection connection = null;
static Statement statement = null;
static ResultSet result = null;
static String request = "";
public static void main (String[] args) {
System.out.println("will load driver");
loadingDrive();
System.out.println("will connect");
connection();
}
public static void loadingDrive() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch ( ClassNotFoundException e ) {
e.getMessage();
}
}
public static void connection() {
try
{
connection = (Connection) DriverManager.getConnection(url, login, password);
System.out.println("Connected");
statement = (Statement) connection.createStatement();
result = statement.executeQuery(request);
}
catch ( SQLException e )
{
System.out.println(e.getMessage());
} finally {
if ( result != null ) {
try {
result.close();
} catch ( SQLException ignore ) {
}
}
if ( statement != null ) {
try {
statement.close();
} catch ( SQLException ignore ) {
}
}
if ( connection != null ) {
try {
connection.close();
} catch ( SQLException ignore ) {
}
}
}
}
}
以下是控制台中的结果:
will load driver
will connect
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
我在文件WebContent / WEB-INF / lib中有连接器(mysql-connector-java-5.1.41-bin.jar)。
我在我的mac上安装了mySQL。 我安装了MAMP,我可以到达phpmyadmin并添加一个新的数据库,但它有点奇怪,虽然phpmyadmin已经记录为默认值并单击“退出”按钮不会断开我我不知道为什么..
phpmyadmin的网址是: http://localhost:8888/phpmyadmin/index.php
为什么我无法连接到mySQL?
编辑: 在检查了MAMP上的mySQL端口后,我用正确的端口(8889)更改了我的URL,但是控制台的输出没有任何改变。
答案 0 :(得分:1)
MySQL和phpMyAdmin不能在同一个端口上。
您确定您的MySQL没有在默认端口上运行吗? 3306
更新:
如果您尚未使用Maven,请执行此操作。它将帮助您管理包裹。这样您就可以避免使用您的方法:loadingDrive()
我刚用测试数据库在本地运行代码。它适用于我。
我对您的代码进行了以下更改:
我删除了loadingDrive()
已将request
更改为static String request = "SELECT 1";
。如果与数据库的连接正常工作,此查询字符串可用于测试。
我将请求打印到控制台:
result = statement.executeQuery(request);
System.out.println(result.next());
我将mysql jdbc连接器添加到我的pom.xml文件中:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
在此之后我运行了代码,这是控制台输出:
will connect
Connected
true
我仍然认为您的MySQL端口是错误的。你在本地运行MySQL吗?你能用phpMyAdmin连接到它吗?
我尝试更改url
以包含错误的端口。然后我收到了:
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
所以我坚信你的端口是错误的。您可以尝试将url
更改为以下内容吗?
static String url = "jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false";