连接数据库的步骤如下:
-
加载驱动程序:在Java代码中加载数据库驱动程序,可以使用
Class.forName()
方法加载驱动程序类。 -
建立数据库连接:创建一个
Connection
对象,指定数据库的连接信息,包括数据库的URL、用户名和密码。可以使用DriverManager.getConnection()
方法来建立连接。 -
创建Statement对象:使用
Connection
对象的createStatement()
方法创建一个Statement
对象,用于发送SQL语句到数据库并获取执行结果。 -
执行SQL语句:使用
Statement
对象的executeQuery()
方法执行SQL查询语句,或者使用executeUpdate()
方法执行更新操作,如插入、更新或删除数据。 -
处理查询结果:如果执行的是查询语句,可以使用
ResultSet
对象来获取查询结果。 -
关闭数据库连接:使用
Connection
对象的close()
方法关闭数据库连接,释放资源。
下面是一个示例代码,演示如何连接到MySQL数据库:
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
try {
// 加载MySQL驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
// 创建Statement对象
Statement statement = connection.createStatement();
// 执行查询语句
String sql = "SELECT * FROM employee";
ResultSet resultSet = statement.executeQuery(sql);
// 处理查询结果
while(resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// ...
System.out.println("id: " + id + ", name: " + name);
}
// 关闭数据库连接
resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}