一、配置MySQL数据库连接器
在连接MySQL之前,首先需要下载MySQL JDBC Driver,将下载下来的jar文件放置到eclipse项目的Libraries中。
├── Libraries │ └── MySQL JDBC Driver.jar └── src
然后,在eclipse的菜单中选择Window->Preferences->Data Management->Connectivity->Driver Definitions,点击“New Driver Definition”添加MySQL的驱动。
填写如下信息:
- Driver Name:MySQL JDBC Driver
- Database Type:MySQL
- Vendor:MySQL Connector/J
- JAR List:选择MySQL驱动jar包
- Class Name:com.mysql.jdbc.Driver
二、创建数据库连接
完成MySQL数据库连接器的配置之后,即可创建MySQL数据库连接,选择菜单Window->Show View->Other->Data Management->Data Source Explorer,在Data Source Explorer窗口右键点击“New”,选择“Database Connection”
填写如下信息:
- Connection profile:
- Driver:选择MySQL JDBC Driver
- URL填写其中一个数据库地址:
- jdbc:mysql://localhost:3306/数据库名
- jdbc:mysql://IP地址:3306/数据库名
- User Name:填写数据库的用户名
- Password:填写数据库密码
点击“Test Connection”测试是否连接成功,连接成功后点击“OK”保存设置。
三、编写Java程序连接MySQL数据库
使用JDBC编写Java代码连接MySQL数据库,示例如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLConnectDemo {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//加载MySQL的JDBC驱动
Class.forName("com.mysql.jdbc.Driver");
//建立MySQL连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名", "用户名","密码");
//创建Statement对象
statement = connection.createStatement();
//查询表的数据
resultSet = statement.executeQuery("select * from table");
while (resultSet.next()) {
//获取每行数据
String column1 = resultSet.getString("column1");
String column2 = resultSet.getString("column2");
//输出结果
System.out.println(column1 + "\t" + column2);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
四、总结
以上就是使用eclipse连接MySQL数据库的全部步骤,需要注意的是,连接MySQL数据库需要正确配置MySQL JDBC Driver和MySQL连接地址,另外,在Java程序中需要加载MySQL的JDBC驱动,建立MySQL连接,执行SQL语句以及关闭连接等操作。
原创文章,作者:SLZRG,如若转载,请注明出处:https://www.506064.com/n/317118.html
微信扫一扫
支付宝扫一扫