1、导入相关jar包
这里创建简单的maven项目,我们导入相关的jar包
相关依赖:
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency>
2、连接数据库,执行查询语句
package JdbcTest;
import java.sql.*;public class DataJdbcTest {public static void main(String[] args) {Connection connection = null;try {// 加载MySQL JDBC驱动程序 Class.forName("com.mysql.jdbc.Driver");// 连接数据库 String url = "jdbc:mysql://localhost:3306/cloud_user";String username = "root";String password = "123456";connection = DriverManager.getConnection(url, username, password);// 连接成功后输出一条消息 System.out.println("成功连接到数据库!");// 在这里可以执行SQL查询和其他数据库操作...//1.创建Statement对象Statement statement = connection.createStatement();//2.执行查询语句String sql = "select * from tb_user";ResultSet resultSet = statement.executeQuery(sql);//3.处理查询结果while (resultSet.next()) {// 读取结果集中的数据int id = resultSet.getInt("id");String name = resultSet.getString("username");String address = resultSet.getString("address");System.out.println("id= "+ id + "username= "+ name + "address= "+address);}} catch (ClassNotFoundException e) {e.printStackTrace();System.out.println("无法加载MySQL JDBC驱动程序");} catch (SQLException e) {e.printStackTrace();System.out.println("无法连接到数据库");} finally {// 关闭连接前输出一条消息 System.out.println("正在关闭数据库连接...");// 关闭连接 if (connection != null) {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}System.out.println("数据库连接已关闭!");}}
}
运行结果: