[英]mySQL connection won't work
我只是无法使用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的URL是: http:// localhost:8888 / phpmyadmin / index.php
为什么我不能连接到MySQL?
编辑:我在检出MAMP上的mySQL端口后,用正确的端口(8889)更改了URL,但在控制台的输出中未进行任何更改。
MySQL和phpMyAdmin不能在同一端口上。
您确定您的MySQL没有在默认端口上运行吗? 3306
更新:
如果您尚未使用Maven,请这样做。 它将帮助您管理包裹。 这样,您可以避免使用方法: loadingDrive()
我只是用测试数据库在本地运行您的代码。 对我来说很好。
我对您的代码进行了以下更改:
我删除了对static String request = "SELECT 1";
的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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.