导入依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
连接数据库
?创建package
?写代码,其中的异常全抛出,实际应用时注意使用try-catch语句,避免异常发生
package com.kuang.test;
import java.sql.*;
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "333";
//1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2、创建连接类,连接数据库,该类代表了数据库
Connection conn = DriverManager.getConnection(url, username, password);
//3、获取声明对象Statement
Statement stat = conn.createStatement();
//4、编写SQL语句
String sql = "select * from jdbc.users";
//5、执行SQL语句并返回结果集,获取的声明对象Statement可以向数据库发送SQL语句
ResultSet rs = stat.executeQuery(sql);
//5、遍历输出结果
while (rs.next()){
System.out.println("id = " + rs.getObject("id"));
System.out.println("name = " + rs.getObject("name"));
System.out.println("password = " + rs.getObject("password"));
System.out.println("email = " + rs.getObject("email"));
System.out.println("birthday = " + rs.getObject("birthday"));
}
//6、关闭连接,释放资源(一定要做),后开的先关闭
rs.close();
stat.close();
conn.close();
}
}
?
?
|