package com.hx.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
public class MysqlConnect {
public static void main(String[] args) throws ClassNotFoundException {
// 数据库连接参数
String url = "jdbc:mysql://127.0.0.1:3306/test";
String user = "root";
String password = "root";
try {
// 加载MySQL驱动
Class.forName("com.mysql.jdbc.Driver");
// 创建连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("连接成功!");
// 创建Statement对象
Statement statement = connection.createStatement();
// 执行SQL语句
String sql = "SELECT * FROM employees";
ResultSet resultSet = statement.executeQuery(sql);
// 处理结果集
while (resultSet.next()) {
int id = resultSet.getInt("emp_no");
String name = resultSet.getString("first_name");
// ... 其他字段
System.out.println("id: " + id + ", name: " + name);
}
// 关闭资源
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
// 处理异常的代码
e.printStackTrace();
}
}
}
java连接mysql
最新推荐文章于 2024-11-13 20:43:20 发布