Spring Jdbc的基本使用

2021-10-02 21:57:13 字數 3606 閱讀 8434

jdbc已經能夠滿足大部分使用者最基本的需求,但是在使用jdbc時,必須自己來管理資料庫資源如:獲取preparedstatement,設定sql語句引數,關閉連線等步驟。

spring對資料庫的操作在jdbc上面做了深層次的封裝,使用spring的注入功能,可以把datasource註冊到jdbctemplate之中。

​jdbctemplate是spring的一部分。jdbctemplate處理了資源的建立和釋放。他幫助我們避免一些常見的錯誤,比如忘了總要關閉連線。他執行核心的jdbc工作流,如statement的建立和執行,而我們只需要提供sql語句和提取結果。

jdbctemplate主要提供以下五類方法:

在springboot專案中引入spring jdbc

資料庫配置:

spring.datasource.driver-class-name=org.postgresql.driver

spring.datasource.url=jdbc:postgresql://localhost:5432/s_springjdbc?currentschema=public

spring.datasource.username=postgres

spring.datasource.password=aaaaaa

新增依賴:

>

>

org.springframework.bootgroupid

>

>

spring-boot-starter-jdbcartifactid

>

dependency

>

**示例:

注入jdbctemplate

@autowired

jdbctemplate jdbctemplate;

建立表:

/**

* 建立表

*/@test

void

testexecute()

執行後在資料庫中建立新錶 customer

刪除表:

/**

* 刪除表

*/@test

void

testexecute2()

執行操作後,customer資料表被刪除。

備註:若表不存在,將會丟擲異常:org.springframework.jdbc.badsqlgrammarexception: statementcallback; bad sql grammar [drop table ***]; nested exception is org.postgresql.util.psqlexception: error: table 「cc」 does not exist。

新增資料:

/**

* 插入資料,不帶引數

*/@test

void

testupdateinsert()

/** * 插入資料,帶引數

*/@test

void

testupdateinsert2()

/** * 插入資料,帶引數

*/@test

void

testupdateinsert3()

更新資料:

/**

* 更新資料,不帶引數

*/@test

void

testupdateupdate1()

/** * 更新資料,帶引數

*/@test

void

testupdateupdate2()

);system.out.

println

("更新了"

+num+

"條資料!");

}

@test

void

testupdatedelete1()

/**

* 新增資料,批量

*/@test

void

testbatchupdate()

system.out.

println

("共插入了"

+sum+

"條資料!");

}/**

* 更新資料

*/@test

void

testbatchupdate2()

; object[

] batchargs2 =

newobject

; object[

] batchargs3 =

newobject

; list

]> argslist =

newarraylist

<

>()

; argslist.

add(batchargs1)

; argslist.

add(batchargs2)

; argslist.

add(batchargs3)

;int

counts = jdbctemplate.

batchupdate

(sql, argslist)

;int sum=0;

for(

int i=

0;i) system.out.

println

("共更新了"

+sum+

"條資料!");

}

預置表資料:

* 查詢資料

*/@test

void

testqueryforlist()

);}/**

* 查詢資料

*/@test

void

testqueryforlist2());}

/**

* 資料查詢

*/@test

void

testqueryformap()

/**

* 資料查詢,queryforobject返回單個實體

*/@test

void

testqueryforobject()

@test

void

testquery());}

參考:

Spring JDBC模版基本操作示例

clob blob author yunhongtao public class examplespringlobdao extends jdbcdaosupport 更新clob欄位的方法示例 param name param text param id throws dataacces cept...

spring jdbc查詢時使用IN 的技巧

在使用select查詢時in比or的效率好。那麼在spring中如何使用in 呢?這是我原來的使用方式,用字串拼接 stringbuilder buf new stringbuilder select name from pos user where id in ids 是list型別 for in...

spring jdbc 使用匿名引數查詢

在經典的 jdbc 用法中,sql 引數是用佔位符 表示,並且受到位置的限制.定位引數的問題在於,一旦引數的順序發生變化,就必須改變引數繫結.在 spring jdbc 框架中,繫結 sql 引數的另一種選擇是使用匿名引數 named parameter 匿名引數 sql 按名稱 以冒號開頭 而不是...