如何用java连接Mysql
时间: 2024-03-10 22:44:35 浏览: 12
使用Java连接Mysql需要进行以下步骤:
1. 加载Mysql驱动程序:在Java中连接Mysql需要使用Mysql提供的驱动程序,需要先将驱动程序加载到内存中。通常使用Class.forName()方法来加载Mysql驱动程序。
2. 建立连接:使用DriverManager.getConnection()方法来建立和Mysql数据库的连接。
3. 创建Statement对象:使用Connection.createStatement()方法创建Statement对象,用于执行SQL语句。
4. 执行SQL语句:使用Statement对象执行SQL语句,例如执行查询操作可以使用executeQuery()方法,执行更新操作可以使用executeUpdate()方法。
5. 处理结果集:如果执行查询操作,可以使用ResultSet对象来获取查询结果。
6. 关闭连接:使用Connection.close()方法关闭连接。
下面是一个示例代码:
```java
import java.sql.*;
public class MysqlConnector {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载Mysql驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
// 创建Statement对象
stmt = conn.createStatement();
// 执行SQL语句
rs = stmt.executeQuery("SELECT * FROM user");
// 处理结果集
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("name: " + name + ", age: " + age);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
注:此示例中的数据库连接信息和SQL语句需要根据实际情况进行修改。