最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解JDBC使用

 更新時間:2017年05月02日 14:57:33   作者:五月的倉頡  
JDBC(Java Database Connectivity),即Java數(shù)據(jù)庫連接,是一種用于執(zhí)行SQL語句的Java API,可以為多種關系數(shù)據(jù)庫提供同一訪問,它由一組用Java語言編寫的類和接口組成。

什么是JDBC

JDBC(Java Database Connectivity),即Java數(shù)據(jù)庫連接,是一種用于執(zhí)行SQL語句的Java API,可以為多種關系數(shù)據(jù)庫提供同一訪問,它由一組用Java語言編寫的類和接口組成。JDBC提供了一種基準,根據(jù)這種基準可以構建更高級的工具和接口,使數(shù)據(jù)庫開發(fā)人員能夠編寫數(shù)據(jù)庫應用程序??偠灾?,JDBC做了三件事:

1、與數(shù)據(jù)庫建立連接

2、發(fā)送操作數(shù)據(jù)庫的語句

3、處理結果

JDBC簡單示例

下面的代碼演示了如何利用JDBC從數(shù)據(jù)庫中查詢若干條符合要求的數(shù)據(jù)出來,使用的數(shù)據(jù)庫是MySql。

1、建立一個數(shù)據(jù)庫和一張表,我的習慣是在CLASSPATH底下建立一個.sql的文件用于存放sql語句

create database school;

use school;

create table student
(
  studentId      int         primary key  auto_increment  not null,
  studentName    varchar(10)                              not null,
  studentAge    int,
  studentPhone  varchar(15)
)

insert into student values(null,'Betty', '20', '00000000');
insert into student values(null,'Jerry', '18', '11111111');
insert into student values(null,'Betty', '21', '22222222');
insert into student values(null,'Steve', '27', '33333333');
insert into student values(null,'James', '22', '44444444');
commit;

2、建立一個.properties文件用于存儲MySql連接的幾個屬性。為什么要建立.properties而不在代碼里面寫死,由于這個并不是Java設計模式的分類,就不細講了,只需要記?。?strong>從設計的角度看,把內容寫在配置文件中永遠好過把內容寫死在代碼中。

mysqlpackage=com.mysql.jdbc.Driver
mysqlurl=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8
mysqlname=root
mysqlpassword=root

3、根據(jù)表字段建立實體類

public class Student
{
  private int    studentId;
  private String  studentName;
  private int    studentAge;
  private String  studentPhone;
  
  public Student(int studentId, String studentName, int studentAge,
      String studentPhone)
  {
    this.studentId = studentId;
    this.studentName = studentName;
    this.studentAge = studentAge;
    this.studentPhone = studentPhone;
  }
  
  public int getStudentId()
  {
    return studentId;
  }

  public String getStudentName()
  {
    return studentName;
  }

  public int getStudentAge()
  {
    return studentAge;
  }

  public String getStudentPhone()
  {
    return studentPhone;
  }

  public String toString()
  {
    return "studentId = " + studentId + ", studentName = " + studentName + ", studentAge = " +
        studentAge + ", studentPhone = " + studentPhone;
  }
}

4、寫一個DBConnection類專門用于向外提供數(shù)據(jù)庫連接。我這里用了MySql,所以只有一個mysqlConnection,如果還用到了Oracle,當然還可以向外提供一個oracleConnection。把這些連接設為全局的可能有人會想是否會有線程安全問題,這是一個很好的問題。那因為我們只從Connection里面讀取一個PreparedStatement出來,而不會去寫它,只讀不修改,是不會引發(fā)線程安全問題的。另外把Connection設置為static的保證了Connection在內存中只有一份,不會占多大資源,每次使用完不調用close()方法去關閉它也沒事。

public class DBConnection
{  
  private static Properties properties = new Properties();
  
  static
  {
    /** 要從CLASSPATH下取.properties文件,因此要加"/" */
    InputStream is = DBConnection.class.getResourceAsStream("/db.properties");
    try
    {
      properties.load(is);
    } 
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
  
  /** 這個mysqlConnection只是為了用來從里面讀一個PreparedStatement,不會往里面寫數(shù)據(jù),因此沒有線程安全問題,可以作為一個全局變量 */
  public static Connection mysqlConnection = getConnection();
  
  public static Connection getConnection()
  {
    Connection con = null;
    try
    {
      Class.forName((String)properties.getProperty("mysqlpackage"));
      con = DriverManager.getConnection((String)properties.getProperty("mysqlurl"), 
          (String)properties.getProperty("mysqlname"), 
          (String)properties.getProperty("mysqlpassword"));
    } 
    catch (ClassNotFoundException e)
    {
      e.printStackTrace();
    } 
    catch (SQLException e)
    {
      e.printStackTrace();
    }
    return con;
  }
}

5、建立一個工具類,用來寫各種方法,專門和數(shù)據(jù)庫進行交互。這種工具類最好搞成單例的,這樣就不用每次去new出來了(實際上new出來也沒看出來會有什么好處),節(jié)省資源

package com.xrq.test11;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class StudentManager
{
  private static StudentManager instance = new StudentManager();
  
  private StudentManager()
  {
    
  }
  
  public static StudentManager getInstance()
  {
    return instance;
  }
  
  public List<Student> querySomeStudents(String studentName) throws Exception
  {
    List<Student> studentList = new ArrayList<Student>();
    Connection connection = DBConnection.mysqlConnection;
    PreparedStatement ps = connection.prepareStatement("select * from student where studentName = ?");
    ps.setString(1, studentName);
    ResultSet rs = ps.executeQuery();
    
    Student student = null;
    while (rs.next())
    {
      student = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4));
      studentList.add(student);
    }
    
    ps.close();
    rs.close();
    return studentList;
  }
}

6、寫個main函數(shù)去調用一下

List<Student> studentList = new ArrayList<Student>();
    studentList = StudentManager.getInstance().querySomeStudents("Betty");
    for (Student student : studentList)
      System.out.println(student);

7、看一下運行結果,和數(shù)據(jù)庫里面的一樣,成功

studentId = 1, studentName = Betty, studentAge = 20, studentPhone = 00000000
studentId = 3, studentName = Betty, studentAge = 21, studentPhone = 22222222 

為什么要使用占位符"?"

看一下第5點,大家一定注意到了,寫sql語句的時候用了"?"占位符,當然有美化代碼的因素,不用占位符就要在括號里寫"+"來拼接參數(shù),如果要拼接的參數(shù)一多,代碼肯定不好看,可讀性不強。但是除了這個原因,還有另外一個重要的原因,就是避免一個安全問題。假設我們不用占位符寫sql語句,那"querySomeStudents(String name) throws Exception"方法就要這么寫:

public List<Student> querySomeStudents(String studentName) throws Exception
{
  List<Student> studentList = new ArrayList<Student>();
  Connection connection = DBConnection.mysqlConnection;
  PreparedStatement ps = connection.prepareStatement("select * from student where studentName = '" + studentName + "'");
  ResultSet rs = ps.executeQuery();
    
  Student student = null;
  while (rs.next())
  {
    student = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4));
    studentList.add(student);
  }
    
  ps.close();
  rs.close();
  return studentList;
}

上面的main函數(shù)一樣可以獲取到兩條數(shù)據(jù),但是問題來了,如果我這么調用呢:

public static void main(String[] args) throws Exception
  {
    List<Student> studentList = new ArrayList<Student>();
    studentList = StudentManager.getInstance().querySomeStudents("' or '1' = '1");
    for (Student student : studentList)
      System.out.println(student);
  }

看下運行結果:

studentId = 1, studentName = Betty, studentAge = 20, studentPhone = 00000000
studentId = 2, studentName = Jerry, studentAge = 18, studentPhone = 11111111
studentId = 3, studentName = Betty, studentAge = 21, studentPhone = 22222222
studentId = 4, studentName = Steve, studentAge = 27, studentPhone = 33333333
studentId = 5, studentName = James, studentAge = 22, studentPhone = 44444444

為什么?看下拼接之后的sql語句就知道了:

select * from student where studentName = '' or '1' = '1'

'1'='1'永遠成立,所以前面的查詢條件是什么都沒用。這種問題是有應用場景的,不是隨便寫一下。Java越來越多的用在Web上,既然是Web,那么查詢的時候有一種情況就是用戶輸入一個條件,后臺獲取到查詢條件,拼接sql語句查數(shù)據(jù)庫,有經(jīng)驗的用戶完全可以輸入一個"‘'' or '1' = '1",這樣就拿到了庫里面的所有數(shù)據(jù)了。

JDBC事物

談數(shù)據(jù)庫必然離不開事物,事物簡單說就是"要么一起成功,要么一起失敗"。那簡單往前面的StudentManager里面寫一個插入學生信息的方法:

public void addStudent(String studentName, int studentAge, String studentPhone) throws Exception
{
  Connection connection = DBConnection.mysqlConnection;
  PreparedStatement ps = connection.prepareStatement("insert into student values(null,?,?,?)");
  ps.setString(1, studentName);
  ps.setInt(2, studentAge);
  ps.setString(3, studentPhone);
  if (ps.executeUpdate() > 0)
    System.out.println("添加學生信息成功");
  else
    System.out.println("添加學生信息失敗");  
}
public static void main(String[] args) throws Exception
{
  StudentManager.getInstance().addStudent("Betty", 17, "55555555");
}

運行就不運行了,反正最后結果是"添加學生信息成功",數(shù)據(jù)庫里面多了一條數(shù)據(jù)。注意一下:

1、增刪改用的是executeUpdate()方法,因為增刪改認為都是對數(shù)據(jù)庫的更新

2、查詢用的是executeQuery()方法,看名字就知道了"Query",查詢嘛

可能有人注意到一個問題,就是Java代碼在insert后并沒有對事物進行commit,數(shù)據(jù)就添加進數(shù)據(jù)庫了,也能查出來,這是為什么呢?因為JDK的Connection設置了事物的自動提交。如果在addStudent(...)方法里面這么寫:

Connection connection = DBConnection.mysqlConnection;
connection.setAutoCommit(false);

autoCommit這個屬性原來是true,JDK自然會幫助開發(fā)者自動提交事物了。OK,如果要改成手動提交事物的代碼,那么應該這么寫addStudent(...)方法:

public void addStudent(String studentName, int studentAge, String studentPhone) throws Exception
{
  Connection connection = DBConnection.mysqlConnection;
  connection.setAutoCommit(false);
  PreparedStatement ps = connection.prepareStatement("insert into student values(null,?,?,?)");
  ps.setString(1, studentName);
  ps.setInt(2, studentAge);
  ps.setString(3, studentPhone);
  try
  {
    ps.executeUpdate();
    connection.commit();
  } 
  catch (Exception e)
  {
    e.printStackTrace();
    connection.rollback();
  }
}

要記得拋異常的時候利用rollback()方法回滾掉事物。

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!

相關文章

  • Spring?Security中自定義cors配置及原理解析

    Spring?Security中自定義cors配置及原理解析

    在Spring框架中,通過自定義CORS配置可根據(jù)實際情況調整URL的協(xié)議、主機、端口等,以適應"同源安全策略",配置原理涉及CorsConfigurer和CorsFilter,自定義配置需要注意@Configuration注解、方法名以及可能的@Autowired注解
    2024-10-10
  • Java發(fā)展史之Java由來

    Java發(fā)展史之Java由來

    本文主要給大家簡單講解了一下java的發(fā)展史,詳細說明了java的由來以及如何一步步發(fā)展起來的,想了解的小伙伴可以來參考下
    2016-10-10
  • springboot全局字符編碼設置解決亂碼問題

    springboot全局字符編碼設置解決亂碼問題

    這篇文章主要介紹了springboot全局字符編碼設置解決亂碼問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-09-09
  • Spring Boot 簡單使用EhCache緩存框架的方法

    Spring Boot 簡單使用EhCache緩存框架的方法

    本篇文章主要介紹了Spring Boot 簡單使用EhCache緩存框架的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • Java的stream流多個字段排序的實現(xiàn)

    Java的stream流多個字段排序的實現(xiàn)

    本文主要介紹了Java的stream流多個字段排序的實現(xiàn),主要是兩種方法,第一種是固定多個字段排序和第二種動態(tài)字段進行排序,具有一定的參考價值,感興趣的可以了解一下
    2023-10-10
  • Java中的位運算符、移位運算詳細介紹

    Java中的位運算符、移位運算詳細介紹

    這篇文章主要介紹了Java中的位運算符、移位運算,有需要的朋友可以參考一下
    2013-12-12
  • Spring整合Mybatis框架方法剖析

    Spring整合Mybatis框架方法剖析

    這篇文章主要為大家介紹了Spring整合Mybatis框架方法剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-07-07
  • SpringCloud Alibaba使用Seata處理分布式事務的技巧

    SpringCloud Alibaba使用Seata處理分布式事務的技巧

    在傳統(tǒng)的單體項目中,我們使用@Transactional注解就能實現(xiàn)基本的ACID事務了,隨著微服務架構的引入,需要對數(shù)據(jù)庫進行分庫分表,每個服務擁有自己的數(shù)據(jù)庫,這樣傳統(tǒng)的事務就不起作用了,那么我們如何保證多個服務中數(shù)據(jù)的一致性呢?跟隨小編一起通過本文了解下吧
    2021-06-06
  • 如何把本地jar包導入maven并pom添加依賴

    如何把本地jar包導入maven并pom添加依賴

    這篇文章主要介紹了如何把本地jar包導入maven并pom添加依賴,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-11-11
  • 使用springboot配置和占位符獲取配置文件中的值

    使用springboot配置和占位符獲取配置文件中的值

    這篇文章主要介紹了使用springboot配置和占位符獲取配置文件中的值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02

最新評論

永靖县| 乌兰县| 丰城市| 宽甸| 宿州市| 遵化市| 图们市| 湾仔区| 绿春县| 阳东县| 金川县| 利津县| 泊头市| 壶关县| 东平县| 巨鹿县| 栾川县| 中江县| 万山特区| 达拉特旗| 邹平县| 全州县| 册亨县| 西城区| 赞皇县| 健康| 云南省| 浦县| 原阳县| 虹口区| 加查县| 当阳市| 德令哈市| 太白县| 大田县| 澳门| 郸城县| 上林县| 宝坻区| 哈尔滨市| 本溪|