我正在使用MySQL 5.5及其默认值。我创建了一个用户/密码并运行了一个脚本来创建一个名为employees的数据库。通过命令提示符,我可以访问数据库:
mysql -u user -p
SELECT * FROM employees
在我的Java应用程序中,我无法连接。我已经尝试过这些URL以及其他URL,但没有任何作用:
"jdbc:mysql://localhost/employees" "user" "password"
"jdbc:mysql://localhost:3306/employees" "user" "password"
"jdbc:mysql:///employees?user=user&password=password"
以下是相关代码:
public Main()
{
try {
connection = DriverManager.getConnection(url);
//connection = DriverManager.getConnection(url, user, password);
// I don't know what else to try
} catch (SQLException ex) {
System.out.print(ex + "\n\n");
}
}
答案 0 :(得分:2)
确保在类路径中有Mysql驱动程序jar并检查MySQL文档:http://dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-basic.html
答案 1 :(得分:0)
错误告诉我
我会使用类似下面的代码片段来获取连接对象。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Connection conn = null;
...
try {
conn =
DriverManager.getConnection("jdbc:mysql://localhost/employees?" +
"user=user&password=password");
// Do something with the Connection
...
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}