一:什么是JDBC
JDBC的全称是Java数据库连接(Java Dalabase Connectivity),它是一套用于执行soL语句的Java API应用程序可通过这套API连接到关系型数据库,并使用SQL语句来完成对数据库中数据的查询、更新、新增和删除的操作
二:实现第一个JDBC程序
在MySQL中创建一个名称为jdbc的数据库,然后在该数据库中创建一个users表,创建数据库和表的SQL语句如下所示。
CREATE DATABASE jdbc;
USE jdbc;
CREATE TABLE users(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(40),
password VARCHAR(40),
email VARCHAR(60),
birthday DATE
)CHARACTER SET utf8 COLLATE utf8_general_ci;
插入数据
INSERT INTO users (NAME, PASSWORD, email, birthday)
VALUES('zs', '123456','zs@sina.com','1980-12-04');
INSERT INTO users (NAME, PASSWORD, email,birthday)
VALUES('lisi','123456','lisi0sina.com','1981-12-04');
INSERT INTO users (NAME, PASSWORD, email,birthday)
VALUES('wangwu','123456','wangwu@sina.com','1979-12-04');
实现结果:
三:编写JDBC程序
1.新建一个名称为chapter02.jdbc.example的包,在该包中创建类Example01,该类用于读取数据库中的users表,并将结果输出到控制台
package chapter12.jdbc.example;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class example01 {
public static void main(String[] args) throws SQLException{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
String sql = "select * from users";
rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String psw = rs.getString("password");
String email = rs.getString("email");
Date birthday = rs.getDate("birthday");
System.out.println(id+" "+name+" "+email+" "+birthday);
}
}catch (ClassNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
}finally {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
rs=null;
}
if (stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
stmt=null;
}
if (conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
conn=null;
}
}
}
}
2.PreparedStatement对象:
在该类中使用PreparedStatement对象对数据库进行插入数据的操作
package chapter12.jdbc.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class example02 {
public static void main(String[] args) throws SQLException{
Connection conn = null;
PreparedStatement preStmt = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url,username,password);
String sql ="INSERT INTO users (NAME, PASSWORD, email,birthday)"+