14 JDBC
什么是JDBC : Java连接数据库!
需要jar包的支持:
- java.sql
- javax.sql
- mysql-conneter-java.... 连接驱动((必须要导入)
导入数据库依赖
<! --mysq1的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysq1-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
CREATE TABLE users(
id lNT 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@qq.com', '2000-01-01');
INSERT INTO users(id, `name`, `password` ,email, birthday)
VALUES(2,'李四';'123456', 'Is@qq.com'; '2000-01-01');
NSERT INTO users(id, `name`, `password`, email, birthday)
VALUES(3,'王五','123456','ww@qq.com' ; '2000-01-01'");
package com.karl.test;
import java.sql.*;
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException,sQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver" );
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url,username,password);
//3.向数据库发送SQL的对象Statement : CRUD
Statement statement = connection.createstatement();
//4.编写SQL
string sql = "select * from users";
//5.执行查询SQL,返回一个Resultset :结果集
Resultset rs = statement.executeQuery(sql);
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();
statement.close();
connection.close();
IDEA中连接数据库
JDBC固定步骤:
- 加载驱动
- 连接数据库,代表数据库
- 向数据库发送SQL的对象Statement : CRUD
- 编写sQL(根据业务,不同的SQL)
- 执行SQL
- 关闭连接
预编译
//1.加载驱动
class.forName( "com.mysq1.jdbc.Driver" ) ;
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url,username,password);
//3.编写SQL
string sql = "insert into users(id,name,password,email, birthday) values (?,?,?,?,?);";
//4.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt( parameterIndex: 1, x: 4);//给第一个占位符?的值赋值为1;
preparedStatement.setString( parameterlndex: 2,x:"狂神说Java");//给第二个占位符?的值赋值为狂神说Java;
preparedStatement.setString( parameterlndex: 3, x:"123456");//给第三个占位符?的值赋值为123456;
preparedStatement . setString( parameterlndex: 4, x:"24736743@qq.com");//给第四个占位符?的值赋值;
preparedStatement.setDate( parameterlndex: 5,new Date(new java.util.Date().getTime()));
//5.执行SQL
int i = preparedstatement.executeUpdate();
if (i>0){
system.out.print1n("插入成功@");
}
//6.关闭连接,释放资源(一定要做)先开后关
preparedStatement.close();
connection.close();