sql 文件
CREATE DATABASE `jdbcStudy` CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `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,'Yoimiya','123456','xiaogong@sina.com','2000-11-24'),
(2,'Xiao','123456','xiao@sina.com','2000-10-24'),
(3,'Fischl','123456','feixieer@sina.com','2000-09-27')
下载JDBC所需jar包,mysql-connector-java-5.1.47(MySQL版本5.7.19),在项目目录下创建lib文件夹,剪切mysql-connector-java-5.1.47.jar到 lib 目录下,右键 lib ,Add as Library。
连接MySQL具体代码实现(查询操作):
package com.hammer.com;
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动(抛异常)
Class.forName("com.mysql.jdbc.Driver");
//用户信息和url 数据库名
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username = "root";
String password = "123456";
//2.连接成功,数据库对象(抛异常)
Connection connection = DriverManager.getConnection(url, username, password);
//3.获取执行SQL对象
Statement statement = connection.createStatement();
//4.执行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("birth = " + resultSet.getObject("birthday"));
System.out.println("----------------------------------------------");
}
//5.释放资源
resultSet.close();
statement.close();
connection.close();
}
}
Statement接口方法
//执行SQL查询语句,返回查询结果集,封装全部查询结果
ResultSet executeQuery(String sql) throws SQLException;
//执行SQL增(INSERT)、删(DELETE)、改(UPDATE)语句,返回受影响的行数
int executeUpdate(String sql) throws SQLException;