Java 中的数据库连接
Connection in Java to a Database
我正在研究 OS X、Eclipse、Java 8 和 MySQLWorkBench。
我意识到最后一个数据库(我可以说模式吗?),名为 "mydb" 位于 localhost:3306(我不知道它到底是什么意思)...
现在我想通过 java 程序连接到这个数据库。
我正在尝试
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb");
跟在错误信息后面
Exception in thread "main" java.sql.SQLException:
No suitable driver found for jdbc:mysql://localhost:3306/mydb
谁能告诉我怎么了?
您需要下载 jdbc 驱动程序并将其添加到您的项目中
Example on how to add the driver in eclipse
您还需要在连接语句中包含用户名和密码,并确保调用 Class for name 以加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection(DB_URL,USER,PASS);
您尚未添加连接 java 应用程序与 MySql 所需的库 database.you 可以从 here 下载它。下载后,只需解压缩 zip无论您 want.And 将其添加到您的项目库文件夹中。
右键单击项目转到 属性 -> java build path -> add external jar .
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","userName","userPass");
其中 userName
是您的数据库用户名,userPass
是与该用户对应的密码。
下载后并将 Connector/J 添加到您的构建路径,如@Jacques 所说。
试试这个代码:
try {
// Load the JDBC driver
@SuppressWarnings("rawtypes")
Class driver_class = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) driver_class.newInstance();
DriverManager.registerDriver(driver);
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", getDbUser(), getDbPassword());
return conn;
} catch (Exception e) {
// TODO: handle exception
}
其中 getDbUser() 是您的数据库用户名,getDbPassword() 是您的数据库密码。
我正在研究 OS X、Eclipse、Java 8 和 MySQLWorkBench。
我意识到最后一个数据库(我可以说模式吗?),名为 "mydb" 位于 localhost:3306(我不知道它到底是什么意思)...
现在我想通过 java 程序连接到这个数据库。 我正在尝试
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb");
跟在错误信息后面
Exception in thread "main" java.sql.SQLException:
No suitable driver found for jdbc:mysql://localhost:3306/mydb
谁能告诉我怎么了?
您需要下载 jdbc 驱动程序并将其添加到您的项目中
Example on how to add the driver in eclipse
您还需要在连接语句中包含用户名和密码,并确保调用 Class for name 以加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection(DB_URL,USER,PASS);
您尚未添加连接 java 应用程序与 MySql 所需的库 database.you 可以从 here 下载它。下载后,只需解压缩 zip无论您 want.And 将其添加到您的项目库文件夹中。 右键单击项目转到 属性 -> java build path -> add external jar .
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","userName","userPass");
其中 userName
是您的数据库用户名,userPass
是与该用户对应的密码。
下载后并将 Connector/J 添加到您的构建路径,如@Jacques 所说。
试试这个代码:
try {
// Load the JDBC driver
@SuppressWarnings("rawtypes")
Class driver_class = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) driver_class.newInstance();
DriverManager.registerDriver(driver);
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", getDbUser(), getDbPassword());
return conn;
} catch (Exception e) {
// TODO: handle exception
}
其中 getDbUser() 是您的数据库用户名,getDbPassword() 是您的数据库密码。