Java基础93 JDBC连接MySQL数据库

时间:2021-08-01 19:37:00

本文知识点(目录):

1、什么是jdbc
    2、jdbc接口的核心API
    3、使用JDBC技术连接MySQL数据库的方法
    4、使用Statement执行sql语句(DDL、DML、DQL)
    5、使用PreparedStatement执行sql语句
    6、使用callablestaement执行sql语句,调用存储过程

7、附录(jdbc连接数据库 实操)
    8、完整的JDBC封装过程,及调用jdbc的使用过程实例



1、什么是jdbc

简单的讲就是:使用java代码(程序)发送sql语句的技术,称为jdbc技术。

2、jdbc接口的核心API

 |-Driver 接口:表示java驱动程序接口。所有的具体的数据库厂商要实现的接口.
|-connect(String url, Properties info):连接数据库的方法
Url:连接数据库的URL
URL语法:jdbc协议:数据库子协议://主机:端口/数据库名
User:数据库的用户名
Password:数据的用户密码
|-DriverManager 类:驱动管理器类,用于管理所有的注册的驱动程序
|-registerDriver(Driver driver):注册驱动类对象
|-getConnection(String url, String user, String password):获取连接对象
|-Connection 接口:表示java程序和数据库的连接对象
|-createStatement()
|-prepareStatement(String sql):创建PreparedStatement对象
|-prepareCall(String sql):创建CallableStatement对象
|-statement 接口:用于执行静态的sql语句
|-executeUpdate(String sql): 执行静态的sql语句(DDL、DML)
|-executeQuery(String sql) :静态的查询sql语句(DQL)
|-PreparedStatement 接口:用于执行预编译sql语句
|-executeUpdate(String sql):执行静态的sql语句(DDL、DML)
|-executeQuery(String sql):静态的查询sql语句(DQL)
|-CallableStatement 接口:用于执行存储过程的sql语句(call xxx)
|-ResultSet 接口:用于封装查询出来的数据
|-next():将光标移到下一行
|-getxxx(int columnIndex):获取列的值有getInt()、getString()、getArray()、getURL() 等等
|-getRow():获取当前行编号。

3、使用JDBC技术连接MySQL数据库的方法

 package com.shore.a_jdbc;

 import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties; /**
* @author DSHORE/2019-3-23
*
*/
//连接MySQL数据库的几种方法
public class connJDBC {
// jdbc协议:数据库的子协议:主机:端口/要连接的数据库名称
private String url = "jdbc:mysql://localhost:3306/school";//连接数据库的URL链接
private String user = "root";//用户名
private String password = "123456";//密码
/*
* 第一种方法:
* */
public void test1() throws Exception{
//1.创建驱动程序类对象
Driver driver = new com.mysql.jdbc.Driver();
//Driver driver = new org.gjt.mm.mysql.Driver();//旧版本的创建方法
//设置用户名密码
Properties props = new Properties();
props.setProperty("user",user);
props.setProperty("password",password);
//2.连接数据库,返回连接对象
Connection conn = driver.connect(url, props);
System.out.println(conn);//返回值:com.mysql.jdbc.JDBC4Connection@29c56c60,表示已连接成功
}
/*
* 第二种方法:使用驱动管理器类连接数据库
* */
public void test2()throws Exception{
//1.创建驱动程序类对象
Driver driver = new com.mysql.jdbc.Driver();//MySQL数据库
//Driver driver2 = new com.oracle.jdbc.Driver();//Oracle数据库
//注册驱动程序(可以注册多个驱动)
DriverManager.registerDriver(driver);
//DriverManager.registerDriver(driver2);
//2.连接数据库
Connection conn=DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
/*
* 第三种方法:使用加载驱动程序类 来注册 驱动程序。(推荐使用这种方式连接数据库)
* */
public void test3() throws Exception{
//通过得到字节码对象的方式加载静态代码块,从而注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
}

4、使用Statement执行sql语句

  4.1、执行DDL语句

 package com.shore.b_statement;

 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement; import org.junit.Test;
/*
*使用statement对象执行静态sql语句(创建表)
**/
public class Demo1 {
//连接数据库的URL
private String url="jdbc:mysql://localhost:3306/school";
//jdbc协议:数据库的子协议:主机:端口/连接的数据库
private String user="root";//用户名
private String password="123456";//密码 //执行DDL语句
@Test
public void test1(){
Statement statement = null;
Connection connection = null;
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
connection = DriverManager.getConnection(url, user, password);
//3.创建statement
statement = connection.createStatement();
//4.准备sql语句
String sql = "CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(32),sex VARCHAR(2));";//创建表
int count = statement.executeUpdate(sql);
System.out.println("影响行数:"+count+"行!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
//5.关闭连接(顺序:后代开的先关闭)
try {
if(statement != null) statement.close();
if(connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

  4.2、执行DML语句

封装工具类(JdbcUtil.java) 文件。(由于连接数据库和关闭资源的那部分代码是不变的,所以将他们封装起来,用到时 就直接调用即可)

 package com.shore.util;

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; public class JdbcUtil { //把固定不变的那部分代码封装起来
//动态连接数据
private static String url = null;
private static String user = null;//用户名
private static String password = null;//密码
private static String driverClass = null;
//静态代码块中(只加载一次)
static{
//读取db.properties
Properties props = new Properties();
try {
FileInputStream fis = new FileInputStream("./src/db.properties");
//加载文件
props.load(fis);
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
driverClass = props.getProperty("driverClass");
//注册驱动
Class.forName(driverClass);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("注册驱动失败");
}
}
//获取连接
public static Connection getConnection(){
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
//释放资源
public static void close(Connection conn,Statement stmt,ResultSet rs){
try {
if(stmt != null) stmt.close();
if(conn != null) conn.close();
if(rs != null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

db.properties配置文件(存储数据库链接、用户及密码等)

 url = jdbc:mysql://localhost:3306/school  //把数据库的链接入口配置在一个文件中,方便以后操作(更改账号密码等等)
user = root
password = 123456
driverClass = com.mysql.jdbc.Driver

执行DML语句 正文

 package com.shore.b_statement;

 import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import org.junit.Test; import com.bw.util.JdbcUtil; /**
* 使用statement执行DML语句(添加、删除、修改数据)
*
*/
public class Demo2 {
/*
* 向student表中添加数据
* */
@Test
public void testInsert(){
ResultSet rs = null;
Connection conn = null;
Statement stmt = null;
//通过工具类获取;连接对象
conn = JdbcUtil.getConnection();
//常见statement对象
try {
stmt=conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
String sql = "INSERT INTO student(NAME,sex) VALUES('张三','女');";
try {
int count = stmt.executeUpdate(sql);
System.out.println(count);
} catch (SQLException e) {
e.printStackTrace();
}
JdbcUtil.close(conn,stmt,rs);
}
/*
* 修改student表中的数据
* */
@Test
public void testUpdate(){
ResultSet rs = null;
Connection conn =null;
Statement stmt = null;
//通过工具类获取;连接对象
conn = JdbcUtil.getConnection();
//常见statement对象
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
String sql = "UPDATE student SET NAME = '王五' WHERE id = 1;";
try {
int count=stmt.executeUpdate(sql);
System.out.println(count);
} catch (SQLException e) {
e.printStackTrace();
}
JdbcUtil.close(conn,stmt,rs);
}
/*
* 删除student表中的数据
* */
@Test
public void testDelete(){
ResultSet rs = null;
Connection conn = null;
Statement stmt = null;
//通过工具类获取;连接对象
conn = JdbcUtil.getConnection();
//常见statement对象
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
String sql = "DELETE FROM student WHERE id = 3;";
try {
int count = stmt.executeUpdate(sql);
System.out.println(count);
} catch (SQLException e) {
e.printStackTrace();
}
JdbcUtil.close(conn,stmt,rs);
}
}

  4.3、执行DQL语句

 package com.shore.b_statement;

 import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import org.junit.Test; import com.bw.util.JdbcUtil; /*
* 使用statement执行sql语句(查询操作语句)
* */
public class Demo3 {
@Test
public void test1(){
ResultSet rs = null;
Connection conn = null;
Statement stmt = null;
//获取连接
conn = JdbcUtil.getConnection();
//创建statement
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
//准备sql语句
String sql = "SELECT * FROM student;";//查询表中所有数据
try {
rs=stmt.executeQuery(sql);
/*//移动光标
boolean flag=rs.next();
if(flag){
//取出值
//索引
int id=rs.getInt(1);
String name=rs.getString(2);
String sex=rs.getString(3);
System.out.println(id+","+name+","+sex);
}*/
//遍历结果
while(rs.next()){
int id=rs.getInt("id");
String name=rs.getString("name");
String sex=rs.getString("sex");
System.out.println(id+","+name+","+sex);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.close(conn, stmt, rs);
}
}
}

5、使用PreparedStatement执行sql语句

 package com.shore.c_prepared;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import org.junit.Test; import com.bw.util.JdbcUtil; /*
* preparedStatement执行sql语句(有效防止sql注入的问题)
* */
public class Demo1 {
//增加
@Test
public void testInsert(){
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
//1.获取连接
conn = JdbcUtil.getConnection();
//2准备预编译的sql
String sql = "INSERT INTO student(NAME,sex) VALUES(?,?);";//?表示一个参数的占位符
try {
//3执行预编译的sql语句(检查语法)
stmt = conn.prepareStatement(sql);
//4.设置参数
stmt.setString(1,"赵六"); //可用name作为参数代表“赵六” 从页面传值来此
stmt.setString(2,"女");
//5.发送参数,执行sql
int count = stmt.executeUpdate();
System.out.println("影响了"+count+"行");
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.close(conn, stmt, rs);
}
}
}

6、使用callablestaement执行sql语句,调用存储过程

MySQL存储过程 相关知识点:https://www.cnblogs.com/dshore123/p/10559182.html

 -- 1.带有输入参数的存储过程
DELIMITER $
CREATE PROCEDURE pro_test(IN sid INT)
BEGIN
SELECT * FROM student WHERE id=sid;
END $ CALL pro_test(2);
 -- 2.执行带有输出参数的存储过程
DELIMITER $
CREATE PROCEDURE pro_test(IN sid INT,OUT sname VARCHAR(32))
BEGIN
SELECT NAME INTO sname FROM student WHERE id=sid;
END $ CALL pro_test(2,@sname);
SELECT @sname;

正文代码

 package com.shore.d_callable;

 import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException; import org.junit.Test; import com.bw.util.JdbcUtil; /**
* 使用CallableSatement调用存储过程
* @author lx
*
*/
public class Demo1 { /*
* 1.带有输入参数的存储过程
* CALL pro_test(2)
* */
@Test
public void test1(){
Connection conn = null;
ResultSet rs = null;
CallableStatement stmt = null;
//获取连接
conn = JdbcUtil.getConnection();
//准备sql
String sql = "CALL pro_test(?);"; //可以执行预编译的sql
try {
//预编译
stmt = conn.prepareCall(sql);
//设置参数
stmt.setInt(1, 2);
//注意:所有的存储过程的sql语句都是使用executeQuery
rs = stmt.executeQuery();
//遍历起结果
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String sex = rs.getString("sex");
System.out.println(id+","+name+","+sex);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.close(conn, stmt, rs);
}
}
/*
*
* 2.执行带有输出参数的存储过程
* */
@Test
public void test2(){
Connection conn = null;
ResultSet rs = null;
CallableStatement stmt = null;
//获取连接
conn = JdbcUtil.getConnection();
//准备sql
String sql = "CALL pro_test(?,?);"; //第一个?是输入参数,第二个?是输出参数
try {
//预编译
stmt = conn.prepareCall(sql);
//设置参数
stmt.setInt(1, 2);
//设置输出参数
/*
*参数 一:参数的位置
*参数二:存储过程中输出参数的jdbc类型 varchar(32)
* */
stmt.registerOutParameter(2,java.sql.Types.VARCHAR);
//发送参数,执行
stmt.executeQuery();
/* //得到输出参数的值
* 索引值:预编译sql中的输出参数的位置
* */
String result = stmt.getString(2);//getxxx方法专门用于获取存储过程中的输出参数
System.out.println(result);
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.close(conn, stmt, rs);
}
}
}

附录

创建表:contact

 create contact(
id varchar(32) primary key,
name varchar(32),
sxe varchar(32),
age int,
phone varchar(32),
email varchar(32),
qq varchar(32)
);

使用“增删改查(CRUD)”操作,连接数据库

 package com.shore.dao.impl;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; import com.shore.dao.ContactDAO;
import com.shore.entity.Contact;
import com.shore.util.JdbcUtil; public class ContactDAOMySqlImpl implements ContactDAO{ //添加数据
public void addContact(Contact contact) {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
conn = JdbcUtil.getConnection();
String sql = "insert into contact(id,name,sex,age,phone,email,qq) values(?,?,?,?,?,?,?)";
try {
//执行预编译的sql语句(检查语法)
stmt = conn.prepareStatement(sql);
String id = UUID.randomUUID().toString().replace("-","");
stmt.setString(1, id);
stmt.setString(2, contact.getName());
stmt.setString(3, contact.getSex());
stmt.setInt(4, contact.getAge());
stmt.setString(5, contact.getPhone());
stmt.setString(6, contact.getEmail());
stmt.setString(7, contact.getQq());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.close(conn, stmt, rs);
}
} //查询所有数据
public List<Contact> finAll() {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
//获取连接
conn = JdbcUtil.getConnection();
String sql = "select * from contact";
try {
//执行预编译的sql语句(检查语法)
stmt = conn.prepareStatement(sql);
//执行sql;
rs = stmt.executeQuery();
List<Contact> list = new ArrayList<Contact>();
while(rs.next()){
//创建Contact对象
Contact c = new Contact();
c.setId(rs.getString("id"));
c.setName(rs.getString("name"));
c.setSex(rs.getString("sex"));
c.setAge(rs.getInt("age"));
c.setPhone(rs.getString("phone"));
c.setEmail(rs.getString("email"));
c.setQq(rs.getString("qq"));
list.add(c);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}finally{
JdbcUtil.close(conn, stmt, rs);
}
} //根据id删除数据
public void delContact(String id) {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
conn = JdbcUtil.getConnection();
String sql = "delete from contact where id=?";
try {
//执行预编译的sql语句(检查语法)
stmt = conn.prepareStatement(sql);
stmt.setString(1,id)
//发送参数,执行sql;
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{//关闭资源
JdbcUtil.close(conn, stmt, rs);
}
} //修改数据
public void updateContact(Contact contact) {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
conn = JdbcUtil.getConnection();
String sql = "update contact set name=?,sex=?,age=?,phone=?,email=?,qq=? where id=?";
try {
//执行预编译的sql语句(检查语法)
stmt=conn.prepareStatement(sql);
stmt.setString(1, contact.getName());
stmt.setString(2, contact.getSex());
stmt.setInt(3, contact.getAge());
stmt.setString(4, contact.getPhone());
stmt.setString(5, contact.getEmail());
stmt.setString(6, contact.getQq());
stmt.setString(7, contact.getId());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.close(conn, stmt, rs);
}
} //根据id查询数据(作用于修改数据的时候)
public Contact findById(String id) {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
//获取连接
conn = JdbcUtil.getConnection();
String sql = "select * from contact where id=?";
try {
//执行预编译的sql语句(检查语法)
stmt = conn.prepareStatement(sql);
stmt.setString(1, id);
rs = stmt.executeQuery();
Contact c = null;
while(rs.next()){
//创建Contact对象
c = new Contact();
c.setId(rs.getString("id"));
c.setName(rs.getString("name"));
c.setSex(rs.getString("sex"));
c.setAge(rs.getInt("age"));
c.setPhone(rs.getString("phone"));
c.setEmail(rs.getString("email"));
c.setQq(rs.getString("qq"));
}
return c;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}finally{
JdbcUtil.close(conn, stmt, rs);
}
} //判断账号昵称是否重复,若重复,页面端显示此账号已存在,请重新取名
public boolean checkContact(String name) {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
//获取数据库的连接
conn = JdbcUtil.getConnection();
//准备sql
String sql = "select * from contact where name = ?";
try {
//执行预编译的sql语句(检查语法)
stmt = conn.prepareStatement(sql);
//设置参数
stmt.setString(1, name);
//发送参数,执行sql
rs = stmt.executeQuery();
if(rs.next()){
return true;
}else{
return false;
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}finally{//关闭资源
JdbcUtil.close(conn, stmt, rs);
}
}
}

完整的JDBC封装过程,及调用jdbc的使用过程实例

db.properties 配置文件(配置了数据库的驱动、入口连接、用户名、密码),主要作用:方便以后修改

 jdbcDriver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/school
userName=root
passWord=123456

JdbcUtils类,把不变动的、且每次都使用到的那部分代码封装起来

 package com.shore.utils;

 import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; /**
* @author DSHORE/2019-5-29
*
*/
public class JdbcUtils {
//静态代码块执行后,这几个参数,就有值了
private static String jdbcDriver = "";
private static String url = "";
private static String userName = "";
private static String passWord = ""; private JdbcUtils() {
} static {//静态代码块
try {
//读取配置文件db.properties,用于获取数据库的入口连接url、用户名、密码,以及数据库的驱动
InputStream inputStream = JdbcUtils.class.getResourceAsStream("/db.properties");
Properties properties = new Properties();
properties.load(inputStream);//加载文件
inputStream.close();
jdbcDriver = properties.getProperty("jdbcDriver");
url = properties.getProperty("url");
userName = properties.getProperty("userName");
passWord = properties.getProperty("passWord");
Class.forName(jdbcDriver); //注册驱动
} catch (Exception e) {
e.printStackTrace();
}
} //获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, userName, passWord);
} //关闭资源(比较严谨的写法)
public static void close(Connection connection, Statement statement,ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}

↑ 此处封装已完成。

下面用个简单的例子来演示怎么使用:

 package com.shore.test;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import org.junit.Test; import com.shore.utils.JdbcUtils; /**
* @author DSHORE/2019-5-29
*
*/
public class jdbcTest { @Test
public void testInsert(){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//1.获取连接
connection = JdbcUtils.getConnection();
//2.准备预编译的sql
String sql = "insert into teacher(sname,sex) values(?,?);";//?表示一个参数的占位符
//3.执行预编译的sql语句(检查语法)
preparedStatement = connection.prepareStatement(sql);
//4.设置参数
preparedStatement.setString(1,"赵六"); //可用name作为参数代表“赵六” 从页面传值来此
preparedStatement.setString(2,"女");
//5.发送参数,执行sql
int count = preparedStatement.executeUpdate();
System.out.println("影响了"+count+"行");
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtils.close(connection, preparedStatement, resultSet);
}
}
}

运行后,结果图:

Java基础93 JDBC连接MySQL数据库

原创作者:DSHORE

作者主页:http://www.cnblogs.com/dshore123/

原文出自:https://www.cnblogs.com/dshore123/p/10582283.html

欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!