MySql--JDBC
2022/2/12 2:12:31
本文主要是介绍MySql--JDBC,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
JDBC概述
● JDBC(Java DataBase Connectivity)java数据库连接
● 是一种用于执行SQL语句的Java API,可以为多种关系型数据库提供统一访问,它由一组用Java语言编写的类和接口组成。
● 不同的数据库实现方式不同,java链接不同的数据库,需要的实现细节不同,有了JDBC,java开发人员只需要编写一次程序,就可以访问不同的数据库
java语言开发者制定一套标准的访问数据库接口
(程序对数据库的操作一般就是增删改查)
不同的数据库开发商具体实现
实现java提供的标准对数据库操作的接口中的方法 save update delete query
程序开发者,只需要学习标准接口的功能
例如:java提供Connection接口,mysql有一个实现类 ConnectionImpl。
mysql开发商将链接mysql具体的实现功能封装到mysql-connector-java-8.0.16.jar文件中,我们连接mysql,只需要将包导入就行
下载地址
JDBC API:
供程序员调用的接口与类,集成在java.sql包中
DriverManager类作用:管理各种不同的jDBC驱动
Connection 接口 与特定数据库的连接
Statement 接口 执行sql
PreparedStatement接口 执行sql
ResultSet接口 接收查询结果
搭建JDBC
Step 1.导入mysql驱动包(实现java标准接口的实现类)
创建目录lib,把jar包导入
Step 2.注册驱动
//这需要初始化驱动程序,这样就可以打开与数据库的通信信道 public static void main(String[] args) { //DriverManager.registerDriver(new Driver()); try { Class.forName("com.mysql.cj.jdbc.Driver");//以java反射机制来创建此类对象 } catch (ClassNotFoundException e) { e.printStackTrace(); } }
Step 3.建立与mysql的连接通道
//characterEncoding=utf8 编码设置 链接mysql8必须设置时区serverTimezone=Asia/Shanghai /* 这需要使用DriverManager.getConnection()方法来创建一个 Connection对象,它代表一个物理连接的数据库. Connection conn =DriverManager.getConnection(URL,USER,PASS); URL:jdbc:mysql://ip(127.0.0.1):端口(3306)/数据库名?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai USER:用户名(root) PASS:密码 */ String url = "jdbc:mysql://127.0.0.1:3306/schooldb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"; try { DriverManager.getConnection(url, "root", "root"); } catch (SQLException throwables) { throwables.printStackTrace(); }
Step 4.向mysql发送sql语句
// Statement 对象 发送sql语句 /* Satement中的方法: Int executeUpdate(String sql) 用于执行ddl语句和dml(增,删,改)语句 返回 操作的行数 用于执行ddl语句返回0 用于执行dml语句返回操作的行数 ResultSet executeQuery(String sql); 用于执行查询语句 返回一个 ResultSet 集合 */ Statement st = connection.createStatement(); st.executeUpdate("insert into major(mname)values('信管')");
Step 5.接受返回结果
● 获得PrepareStatement执行sql语句
● 在sql语句中参数位置使用占位符,使用setXX方法向sql中设置参数
● PrepareStatement ps = connection.prepareStatement(sql);
PrepareStatement中的方法:
Int executeUpdate() 用于执行ddl语句和dml(增,删,改)语句 返回操作的行数
用于执行ddl语句返回0
用于执行dml语句返回操作的行数
ResultSet executeQuery(); 用于执行查询语句 返回一个Result集合
Step 6.关闭连接通道
st.close(); connection.close();
PreparedStatement和Statement
用Statement进行增删,传参时直接将变量拼接到字符中,书写比较复杂,不能防止sql注入
package day01JDBC; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class Demo2 { /* 1.导入驱动包 2.注册驱动 3.建立与mysql的连接通道 4.向mysql发送sql语句 5.接受返回结果 6.关闭连接通道 */ public static void main(String[] args) { try { delete(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public static void delete() throws SQLException, ClassNotFoundException { String id = "7"; Connection connection = null; Statement st = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://127.0.0.1:3306/schooldb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"; connection = DriverManager.getConnection(url, "root", "root"); st = connection.createStatement(); st.executeUpdate("delete from student where id = "+id); } finally { if (st != null) { st.close(); } if (connection != null) { connection.close(); } } } public static void save() throws ClassNotFoundException, SQLException { int num = 107; String name = "tom"; String gender = "男"; String birthday = "2000-9-1"; float height = 1.78f; Connection connection = null; Statement st = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://127.0.0.1:3306/schooldb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"; connection = DriverManager.getConnection(url, "root", "root"); st = connection.createStatement(); st.executeUpdate("insert into student(num,sname,gender,birthday,height)" + "values(" + num + ",'" + name + "','" + gender + "','" + birthday + "'," + height + ")"); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { if (st != null) { st.close(); } if(connection!=null) { connection.close(); } } } }
但是更建议使用PreparedStatement
基于以下的原因:
1、代码的可读性和可维护性. 虽然用PreparedStatement来代替Statement会使代码多出几行,但这样的代码无 论从可读性还是可维护性上来说.都比直接用Statement的代码高很多档次
2、最重要的一点是极大地提高了安全性. 防止sql注入 Stringsql=“ delete from user where id = ”+num; 如果我们把[or 1=1]作为id传入进来? delete from tb_name where id = 1 or 1 = 1; 因为‘1’=‘1’肯定成立 而如果你使用预编译语句.你传入的任何内容就不会和原来的语句发生任何匹 配的关系. 预编译模式中每个占位符处,只能插入一个值,而会过滤其他语句.
//String id = “7 or 1=1”; sql攻击/注入,表会直接清空
package day01JDBC; import java.sql.*; public class Demo3 { /* 1.导入驱动包 2.注册驱动 3.建立与mysql的连接通道 4.向mysql发送sql语句 5.接受返回结果 6.关闭连接通道 */ public static void main(String[] args) { try { //save(); delete(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public static void delete() throws SQLException, ClassNotFoundException { //String id = "7 or 1=1"; sql攻击/注入,表会直接清空 String id = "9"; Connection connection = null; PreparedStatement ps = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://127.0.0.1:3306/schooldb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"; connection = DriverManager.getConnection(url, "root", "root"); //使用PreparedStatement发送sql //预编译sql 再次只是将sql编译到prepareStatement对象中,?称为占位符 表示此处徐亚传入一个值 ps = connection.prepareStatement("delete from student where id = ?"); //向sql中的占位符赋值 ps.setObject(1,id); ps.executeUpdate(); } finally { if(ps!=null){ ps.close(); } if (connection != null) { connection.close(); } } } public static void save() throws ClassNotFoundException, SQLException { int num = 107; String name = "tom"; String gender = "男"; String birthday = "2000-9-1"; float height = 1.78f; Connection connection = null; PreparedStatement ps = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://127.0.0.1:3306/schooldb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"; connection = DriverManager.getConnection(url, "root", "root"); //使用PreparedStatement发送sql //预编译sql 再次只是将sql编译到prepareStatement对象中,?称为占位符 表示此处徐亚传入一个值 ps = connection.prepareStatement("insert into student(num,sname,gender,birthday,height)"+ "values (?,?,?,?,?)"); //向sql中的占位符赋值,赋值时对值进行检测 ps.setObject(1,num); ps.setObject(2,name); ps.setObject(3,gender); ps.setObject(4,birthday); ps.setObject(5,height); ps.executeUpdate(); } finally { if(ps!=null){ ps.close(); } if (connection != null) { connection.close(); } } } }
JDBC查询
PreparedStatement和Statement中的executeQuery()方法中会返回一 个ResultSet对象,查询结果就封装在此对象中.
使用ResultSet中的next()方法获得下一行数据
使用getXXX(String name)方法获得值
1.查询一条结果,//通过学号查询,只返回一条记录
package day01JDBC; import java.sql.*; public class Demo4 { public static void main(String[] args) { try { Student student = query1("102"); System.out.println(student); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public static Student query1(String num) throws SQLException, ClassNotFoundException { Connection connection = null; PreparedStatement ps = null; ResultSet rs = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://127.0.0.1:3306/schooldb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"; connection = DriverManager.getConnection(url, "root", "root"); //查询语句是有返回结果的,如何接收结果 //通过学号查询,只返回一条记录 ps = connection.prepareStatement("select id,num,sname,gender,birthday,height,register_time from student where num = ?"); ps.setObject(1,num); rs = ps.executeQuery();//执行查询语句,接受返回的结果,在java中存储结果 //循环 ResultSet next()将光标移到下一行,如果有数据返回true Student student = new Student(); while (rs.next()){ // System.out.println(rs.getInt(1)); // System.out.println(rs.getInt(2));//不建议用这种 student.setId(rs.getInt("id")); student.setNum(rs.getInt("num")); student.setName(rs.getString("sname")); student.setGender(rs.getString("gender")); student.setBirthday( rs.getDate("birthday")); student.setHeight(rs.getFloat("height")); student.setRegisterTime(rs.getTimestamp("register_time"));//datetime 年月日 时分秒 getTimestamp获取 } return student; } finally { if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } if (connection != null) { connection.close(); } } } }
System.out.println(rs.getInt(1)); System.out.println(rs.getInt(2));
结果
package day01JDBC; import java.util.Date; public class Student { private int id; private int num; private String name; private String gender; private Date birthday; private float height; private Date registerTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public Date getRegisterTime() { return registerTime; } public void setRegisterTime(Date registerTime) { this.registerTime = registerTime; } @Override public String toString() { return "Student{" + "id=" + id + ", num=" + num + ", name='" + name + '\'' + ", gender='" + gender + '\'' + ", birthday=" + birthday + ", height=" + height + ", registerTime=" + registerTime + '}'; } }
调用对象,使用getXXX(“sname”)的方法,返回结果为
2.查询多条记录,//查询性别为男的学生
public static void main(String[] args) { try { List<Student> list = query2("男"); for (Student s : list){ System.out.println(s); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public static List<Student> query2(String gender) throws SQLException, ClassNotFoundException { Connection connection = null; PreparedStatement ps = null; ResultSet rs = null; ArrayList<Student> list = new ArrayList<>();//接收查询到的多条数据记录 try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://127.0.0.1:3306/schooldb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"; connection = DriverManager.getConnection(url, "root", "root"); ps = connection.prepareStatement("select id,num,sname,gender,birthday,height,register_time from student where gender = ?"); ps.setObject(1, gender); rs = ps.executeQuery(); while (rs.next()) { //每循环一次就创建一个学生对象,将当前记录封装到一个学生对象中 Student student = new Student(); student.setId(rs.getInt("id")); student.setNum(rs.getInt("num")); student.setName(rs.getString("sname")); student.setGender(rs.getString("gender")); student.setBirthday(rs.getDate("birthday")); student.setHeight(rs.getFloat("height")); student.setRegisterTime(rs.getTimestamp("register_time"));//datetime 年月日 时分秒 getTimestamp获取 list.add(student); } return list; } finally { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (connection != null) { connection.close(); } } }
运行结果
这篇关于MySql--JDBC的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-15MySQL教程:初学者必备的MySQL数据库入门指南
- 2024-11-15MySQL教程:初学者必看的MySQL入门指南
- 2024-11-04部署MySQL集群项目实战:新手入门教程
- 2024-11-04如何部署MySQL集群资料:新手入门指南
- 2024-11-02MySQL集群项目实战:新手入门指南
- 2024-11-02初学者指南:部署MySQL集群资料
- 2024-11-01部署MySQL集群教程:新手入门指南
- 2024-11-01如何部署MySQL集群:新手入门教程
- 2024-11-01部署MySQL集群学习:新手入门教程
- 2024-11-01部署MySQL集群入门:新手必读指南