一、JDBC的概念
-
什么是JDBC
JDBC是一种可用于执行SQL语句的JAVA API,是链接数据库和JAVA应用程序的纽带 -
JDBC的功能
与数据库建立链接;向数据库发送SQL语句;处理从数据库返回的结果;管理连接和事务。
二、JDBC连接数据库
JDBC连接数据库有六步骤:
1.加载驱动
2.连接数据库
3.向数据库发送sql的对象
4.编写sql
5.执行sql
6.关闭连接,释放资源
准备工作:
1.首先要创建数据表,并插入数据
2.在pom.xml中添加mysql的驱动
<dependencies>
<!-- 导入mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
3.idea连接数据库
输入mysql的账号和密码,选择需要连接的数据库。
完成以上配置之后JDBC连接MySQL(以下六步):
(1)加载驱动
> // 1.加载驱动
> Class.forName("com.mysql.jdbc.Driver");
(2).连接数据库
// 2.连接jdbc数据库
Connection connection=DriverManager.getConnection(url, username, password);
3.向数据库发送sql的对象
// 向数据库发送sql的对象Statement
Statement statement=connection.createStatement();
4.编写sql语句
// 4.编写sql
String sql="select * from users";
5.执行sql语句
// 5.执行sql
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
System.out.println("id="+result.getObject("id"));
System.out.println("name="+result.getObject("name"));
System.out.println("password="+result.getObject("password"));
System.out.println("email="+result.getObject("email"));
System.out.println("birthday="+result.getObject("birthday"));
}
6.关闭连接,释放资源
// 6.关闭连接,释放资源
connection.close();
result.close();
statement.close();
}
总的代码为:
package com.zyc.test;
import java.sql.*;
public class TestJdbc {
public static <CachedJarFile> void main(String[] args) throws ClassNotFoundException,SQLException{
// 配置信息
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.连接jdbc数据库
Connection connection=DriverManager.getConnection(url, username, password);
// 向数据库发送sql的对象Statement
Statement statement=connection.createStatement();
// 4.编写sql
String sql="select * from users";
// 5.执行sql
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
System.out.println("id="+result.getObject("id"));
System.out.println("name="+result.getObject("name"));
System.out.println("password="+result.getObject("password"));
System.out.println("email="+result.getObject("email"));
System.out.println("birthday="+result.getObject("birthday"));
}
// 6.关闭连接,释放资源
connection.close();
result.close();
statement.close();
}
}
文件配置好之后,运行TestJdbc.java:
可正确显示出数据表里的信息,JDBC连接数据库成功。