赞
踩
JDBC(Java DataBase Connectivity) 称为Java数据库连接。链接后,可以使用Java和SQL语言对数据库进行操作。
链接步骤
1. 注册驱动类,其中传入的字符串为导入的依赖中的Driver。
Class.forName("com.mysql.jdbc.Driver");
2. 通过 DriverManager 的 getConnection 方法获取数据库的连接。
- /**
- * 2.连接连接
- * getConnection(String url,String user, String password);
- * url: 连接字符串 (用于表述 要连接那台计算机的数据库 )
- * user :数据库账号
- * password: 数据库密码
- * url: jdbc:mysql://localhost:3306/数据库名称?参数名:参数值
- * jdbc: 协议 mysql:子协议
- * localhost:3306 主机端口
- */
- String url = "jdbc:mysql://localhost:3306/myschool?userUnicod=true&characterEncoding=utf8";
- String user = "root";
- String passwd = "root";
- Connection connection = DriverManager.getConnection(url, user, passwd);
这样就完成了数据库的链接 。那么如何对数据库进行操作呢?接下来需要在以上的步骤后面继续。
对数据库进行操作步骤
3. 获取数据库操作对象statement
Statement statement = connection.createStatement();
4. 执行SQL语句
- //编写SQL语句
- String sql = "UPDATE grade SET gradeName='一年级' WHERE gradeID =1";
- //执行SQL语句,返回值为受影响的行数
- int row = statement.executeUpdate(sql);
对数据库进行操作的完整代码
- // 声明数据库连接
- Connection connection = null;
- // 声明数据库操作对象
- Statement statement =null;
- try {
- Class.forName("com.mysql.jdbc.Driver");
-
- String url = "jdbc:mysql://localhost:3306/myschool?userUnicod=true&characterEncoding=utf8";
- String user = "root";
- String passwodr = "root";
- connection = DriverManager.getConnection(url, user, passwodr);
-
- statement = connection.createStatement();
-
- String sql = "UPDATE grade SET gradeName='一年级' WHERE gradeID =1";
- int row = statement.executeUpdate(sql);
-
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- // 释放资源 正用到关
- if(null!=statement){
- statement.close();
- }
- if (null != connection) {
- connection.close();
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- package cn.xk.demoa;
-
- import cn.xk.entity.Student;
-
- import java.sql.*;
- import java.util.ArrayList;
- import java.util.List;
-
- public class Demo {
- public static void main(String[] args) {
- // 声明数据库连接
- Connection connection = null;
- // 声明数据库操作对象
- Statement statement = null;
- // 声明 查询返回的结果集
- ResultSet resultSet = null;
- // 声明集合 用于保存 学生集
- List<Student> studentList = new ArrayList<>();
- try {
- // 注册驱动类
- Class.forName("com.mysql.jdbc.Driver");
- String url = "jdbc:mysql://localhost:3306/myschool?userUnicod=true&characterEncoding=utf8";
- String user = "root";
- String passwodr = "root";
- // 通过DriverManager的getConnection 方法 获取数据的连接
- connection = DriverManager.getConnection(url, user, passwodr);
-
- System.out.println("数据库连接成功");
- //3.获取数据库操作对象
- statement = connection.createStatement();
- //4.执行SQL语句
- String sql = "select * from student";
- // 通过statement 的executeQuery(sql)方法 执行 查询语句
- // ResultSet 结果集
- resultSet = statement.executeQuery(sql);
- // 遍历结果集 行 和 列 组成的结果集
-
- // 通过next() 方法判断是否存在数据
- while (resultSet.next()) {
- Student student = new Student();
- //通过下标获取 虚拟结果集中的值 注意 下标从1开始 2 3 4 ....
- int stuNo = resultSet.getInt(1);
- student.setStudentNo(stuNo);
- // 通过列名 获取值
- String stuName = resultSet.getString("studentName");
- student.setStudentName(stuName);
- student.setLoginPwd(resultSet.getString("loginPwd"));
- student.setSex(resultSet.getString("sex"));
- student.setGradeId(resultSet.getInt("gradeId"));
- student.setPhone(resultSet.getString("phone"));
- student.setAddress(resultSet.getString("address"));
- student.setBornDate(resultSet.getString("bornDate"));
- // 将对象保存到集合中
- studentList.add(student);
- }
- System.out.println("-----------------");
- for (Student student : studentList)
- System.out.println(student);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- // 释放资源 正用到关
- if (null != resultSet) {
- resultSet.close();
- }
- if (null != statement) {
- statement.close();
- }
- if (null != connection) {
- connection.close();
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
-
- }
- }
运行结果
- Student{studentNo=10001, loginPwd='123', studentName='李文才', sex=男, gradeld=1, phone='13645667890', address='地址不详', bomDate='1994-04-12 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=10002, loginPwd='123', studentName='李斯文', sex=男, gradeld=1, phone='13645556793', address='河南洛阳', bomDate='1993-07-23 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=10003, loginPwd='123', studentName='张萍', sex=女, gradeld=1, phone='13642345112', address='地址不详', bomDate='1995-06-10 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=10004, loginPwd='123', studentName='韩秋洁', sex=女, gradeld=1, phone='13812344566', address='北京市海淀区', bomDate='1995-07-15 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=10005, loginPwd='123', studentName='张秋丽', sex=女, gradeld=1, phone='13567893246', address='北京市东城区', bomDate='1994-01-17 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=10006, loginPwd='123', studentName='肖梅', sex=女, gradeld=1, phone='13563456721', address='河北省石家庄市', bomDate='1991-02-17 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=10007, loginPwd='123', studentName='郭秦洋', sex=男, gradeld=1, phone='13056434411', address='上海市卢湾区', bomDate='1992-04-18 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=10008, loginPwd='123', studentName='何睛睛', sex=女, gradeld=1, phone='13053445221', address='广州市天河区', bomDate='1997-07-23 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=11111, loginPwd='123', studentName='郭靖', sex=男, gradeld=1, phone='13645667783', address='天津市河西区', bomDate='1990-09-08 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=20000, loginPwd='123', studentName='王宝宝', sex=男, gradeld=2, phone='15076552323', address='地址不详', bomDate='1996-06-05 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=20010, loginPwd='123', studentName='何小华', sex=女, gradeld=2, phone='13318877954', address='地址不详', bomDate='1995-09-10 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=30011, loginPwd='123', studentName='陈志强', sex=男, gradeld=3, phone='13689965430', address='地址不详', bomDate='1994-09-27 00:00:00.0', email='null', identityCard='null'}
- Student{studentNo=30012, loginPwd='123', studentName='李露露', sex=女, gradeld=3, phone='13685678854', address='地址不详', bomDate='1992-09-27 00:00:00.0', email='null', identityCard='null'}
使用JDBC实现MySQL的事务只需要在对数据库进行操作之前关闭MySQL的自动事务,并且在操作之后进行提交或者回滚,即可。
例如,完成驱动类注册,并且获取到数据库链接和数据库操作对象后进行如下操作:
- //关闭MySQL的自动事务
- connection.setAutoCommit(false);
- //执行SQL语句,返回受影响的行数
- int row = statement.executeUpdate(sql);
- //未报异常则提交事务
- connection.commit();
-
实现将grade表 gradeID=2 的项的gradeName字段改为“二年级”:
- public static void main(String[] args) {
- Connection connection = null;
- Statement statement = null;
- try {
- //加载驱动类
- Class.forName("com.mysql.jdbc.Driver");
- String url = "jdbc:mysql://localhost:3306/myschool?userUnicod=true&characterEncoding=utf8";
- String user = "root";
- String passwd = "root";
- //获取数据库的链接
- connection = DriverManager.getConnection(url, user, passwd);
- //获取数据库操作对象
- statement = connection.createStatement();
- //关闭自动事务
- connection.setAutoCommit(false);
- String sql = "UPDATE grade SET gradeName='二年级' WHERE gradeID =2";
- //返回受影响行数
- int row = statement.executeUpdate(sql);
- //未出现异常,则提交事务
- connection.commit();
- } catch (Exception e) {
- try {
- //出现异常,回滚
- connection.rollback();
- } catch (SQLException ex) {
- ex.printStackTrace();
- }
- e.printStackTrace();
- }finally {
- try {
- if(statement!=null)
- statement.close();
- if(connection!=null)
- connection.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- }
为了防止SQL注入攻击等,我们需要对要执行的sql语句进行预加载。预加载时,我们需要将sql语句中的值全部替换为 ?(占位符,表示此处有一个值) ,然后再传入,进行执行。
传入的SQL语句格式
SELECT * FROM student WHERE studentNo = ? AND loginPwd = ?
步骤:
1. 连接数据库,通过PerparedStatment传入SQL语句进行预加载,获取到数据库操作对象perparedStatement。
preparedStatement = connection.prepareStatement(sql);
2. 处理占位符,为占位符赋值
- preparedStatement.setObject(1,"10001");
- preparedStatement.setObject(2,"123");
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。