驱动:声卡、显卡、数据库
我们的程序会通过数据库驱动,和数据库打交道!
- CREATE DATABASE jdbcstudy CHARACTER SET utf8 COLLATE utf8_general_ci;
-
- USER jdbcstudy;
-
- CREATE TABLE users(
- `id` INT PRIMARY KEY,
- `name` VARCHAR(40),
- `password` VARCHAR(40),
- `email` VARCHAR(60),
- `birthday` DATE
- );
-
- INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`)
- VALUES(1,'张三','123456','zs@sina.com','1980-12-04'),
- (2,'李四','123456','lisi@sina.com','1981-12-04'),
- (3,'王五','123456','wangwu@sina.com','1982-12-04');
1.创建一个普通项目
2.导入数据库驱动(jar包)
3.编写测试代码
- import java.sql.*;
-
- //我的第一个JDBC程序
- public class JdbcFirstDemo {
- public static void main(String[] args) throws ClassNotFoundException, SQLException {
- //1.加载驱动
- Class.forName("com.mysql.jdbc.Driver"); //固定写法,加载驱动
-
- //2.用户信息和url
- /*
- seUnicode=true(支持中文编码)
- characterEncoding=utf8(设置中文字符集为utf-8)
- useSSL=true(使用安全的连接)
- */
- String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
- String username = "root";
- String password = "123456";
-
- //3.连接成功,数据库对象 Connection 代表数据库
- Connection connection = DriverManager.getConnection(url, username, password);
-
- //4.执行SQL的对象 statement执行sql的对象
- Statement statement = connection.createStatement();
-
- // 5.执行SQL的对象 去 执行SQL,可能存在结果,查看返回结果
- String sql = "SELECT * FROM `users`";
- //返回的结果集,结果集中封装了我们全部的查询出来的结果
- ResultSet resultSet = statement.executeQuery(sql);
- while (resultSet.next()){
- System.out.println("id:" + resultSet.getObject("id"));
- System.out.println("name:" + resultSet.getObject("name"));
- System.out.println("pwd:" + resultSet.getObject("password"));
- System.out.println("email:" + resultSet.getObject("email"));
- System.out.println("birthday:" + resultSet.getObject("birthday"));
- System.out.println("================");
- }
- //6.释放连接
- resultSet.close();
- statement.close();
- connection.close();
- }
- }
返回结果集时,代码.executeQuery是查询;所有的删除和插入都叫更新.executeUpdate()