怎么连接Mysql使用的数据连接包

2023年 9月 18日 18.8k 0

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();
}
}
}

2. Spring JDBC
Spring JDBC是Spring框架提供的一种基于JDBC的数据库访问技术。它不仅封装了JDBC的复杂性,还提供了一些额外的特性,例如:声明式事务、异常转换等。使用Spring JDBC连接MySQL数据库,需要先在项目中添加Spring JDBC依赖,并配置数据源和JdbcTemplate。下面是使用Spring JDBC连接MySQL数据库的示例代码:
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
}
public class SpringJdbcTest {
private static final String SQL_SELECT = "SELECT * FROM user";
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(DataSourceConfig.class);
JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);
List userList = jdbcTemplate.query(SQL_SELECT, new RowMapper() {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
return user;
}
});
for (User user : userList) {
System.out.println(user.getName() + "t" + user.getAge());
}
}
}

怎么连接Mysql使用的数据连接包

除了上述两种方式外,还有一些其他的数据连接包,例如:MyBatis、Hibernate等。开发者可以根据自己的需求和习惯选择不同的数据连接包。连接数据库时需要注意,一定要保护好数据库的安全性,防止出现安全漏洞。

相关文章

Oracle如何使用授予和撤销权限的语法和示例
Awesome Project: 探索 MatrixOrigin 云原生分布式数据库
下载丨66页PDF,云和恩墨技术通讯(2024年7月刊)
社区版oceanbase安装
Oracle 导出CSV工具-sqluldr2
ETL数据集成丨快速将MySQL数据迁移至Doris数据库

发布评论