JDBC随笔

简介

sun公司为了简化开发人员的(对数据库的统一)操作,提供了一个(Java操作数据库的)规范,俗称JDBC。

java.sql

javax.sql

mysql-connecter-java-5.1.47.jar

创建第一个JDBC程序

  1. 创建一个普通项目

  2. 导入数据库驱动

  3. 编写测试程序

     package com.lili.lesson1;
     
     import java.sql.*;
     
     public class JdbcFirstDemo {
         public static void main(String[] args) throws ClassNotFoundException, SQLException {
             //1.加载驱动
             Class.forName("com.mysql.jdbc.Driver");
     
             //2.用户信息和url
             //userUnicode=true&characterEncoding=utf8&useSSL=true 支持中文编码、设定中文字符集utf8、使用安全
             String url = "jdbc:mysql://192.168.133.151:3306/jdbcStudy?userUnicode=true&charset=utf8&useSSL=false&serverTimezone=Asia/Shanghai";
             String username = "root";
             String password = "root";
     
             //3.链接成功,数据库对象
             Connection connection = DriverManager.getConnection(url, username, password);
     
             //4.执行SQL对象
             Statement statement = connection.createStatement();
     
             //5.执行SQL对象 去 对象,可能存在结果,查看返回结果
             String sql = "select * from users";
             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.释放链接
             result.close();
             statement.close();
             connection.close();
        }
     }

statement对象

JDBC中的statement对象用于向数据库发送SQL语句

CRUD操作=create

使用executeUpdate()方法

 Statement st = conn.createStatement();
 String sql = "insert into users()value()";
 int num = st.executeUpdate(sql);
 if(num>0){
     System.out.println("success!");
 }

CRUD-delete

 Statement st = conn.createStatement();
 String sql = "delete from users where id=1";
 int num = st.executeUpdate(sql);
 if(num>0){
     System.out.println("Successfully deleted!");
 }

CRUD-update

 Statement st = conn.createStatement();
 String sql = "update users set name='' where name=''";
 int num = st.executeUpdate(sql);
 if(num>0){
     System.out.println("Modified successfully");
 }

CRUD-read

 Statement st = conn.createStatement();
 String sql = "select * from users where id=1";
 ResultSet rs = st.executeQuery(sql);
 while(rs.next()){
     System.out.println();
    ...
 }

SQL注入问题

sql存在漏洞,会被攻击导致数据泄露

SQL会凭借or出差错

PreparedStatement对象

可以防止SQL注入

事务

ACID原则

原子性:要么全部完成,要么全部失败

一致性:总数不变

隔离性:多个进程互不干扰

持久性:一旦提交不可逆,持久化到数据库

posted @ 2021-03-10 09:00  keepClam  阅读(245)  评论(0)    收藏  举报