怎么连接Mysql使用的数据连接包
MySQL作为一种常用的关系型数据库,连接MySQL数据库成为了很多开发者必须要掌握的技能。在Java开发中,可以通过使用不同的数据连接包来连接MySQL数据库。下面将介绍几种常用的数据连接包。
1. JDBC
JDBC是Java Database Connectivity的缩写,它是Java连接数据库的标准规范。JDBC提供了一组接口,用于访问各种不同类型的数据库,包括MySQL。使用JDBC连接MySQL数据库,需要先下载MySQL Connector/J的jar包,并在项目中添加到类路径中。下面是使用JDBC连接MySQL数据库的示例代码:
public class JdbcTest {
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USERNAME = "root";
private static final String PASSWORD = "password";
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 连接数据库
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
// 执行查询
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM user");
// 处理结果集
while (rs.next()) {
System.out.println(rs.getString("name") + "t" + rs.getInt("age"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 释放资源
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
}
}