当前位置:网站首页>JDBC与连接池
JDBC与连接池
2022-08-03 05:09:00 【*super】
一、定义
JDBC是Java访问数据库的标准规范,真正怎么操作数据库还需要具体的实现类,也就是数据库驱动。每个数据库厂商根据自家数据库的通信格式编写好自己数据库的驱动。所以我们只需要会调用JDBC接口中的方法即可,数据库驱动由数据库厂商提供。
Connection:在java程序和数据库之间建立连接。
Statement:执行sql语句。
ResultSet :接收查询结果数据集。
DriverManager :加载驱动,创建数据库连接对象。
二、JDBC增删改
package cn.JDBC.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @Author:张金贺
* @Date:2022/7/7 17:10
* @Version 1.0
*/
public class demo01 {
public static void main(String[] args) throws SQLException {
Connection conn=null;
Statement st=null;
try {
//加载mysql数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls", "root", "root");
//创建Statement
st = conn.createStatement();
//执行SQL语句
int count= st.executeUpdate("insert into boys(boyName,userCP) values('zhang',1)");
System.out.println(count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}finally {
if (st!=null){
st.close();
}
if (conn!=null) {
conn.close();
}
}
}
}
三、JDBC查询
package cn.JDBC.Test;
import java.sql.*;
/**
* @Author:张金贺
* @Date:2022/7/7 17:37
* @Version 1.0
*/
public class demo02 {
public static void main(String[] args) throws SQLException {
Connection conn=null;
Statement st=null;
try {
//加载mysql数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls", "root", "root");
//创建Statement
st = conn.createStatement();
//执行SQL语句
ResultSet result =st.executeQuery("select * from boys ");
while (result.next()){
System.out.println(result.getInt(1));
System.out.println(result.getString("boyName"));
System.out.println(result.getInt("userCP"));
System.out.println();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}finally {
if (st!=null){
st.close();
}
if (conn!=null) {
conn.close();
}
}
}
}
四、封装查询结果的数据到list集合
package cn.JDBC.Test;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @Author:张金贺
* @Date:2022/7/7 18:38
* @Version 1.0
*/
public class demo03 {
public static void main(String[] args) throws SQLException {
Connection conn =null;
Statement st =null;
ResultSet rs =null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls", "root", "root");
st = conn.createStatement();
rs = st.executeQuery("select * from boys ");
List<Boys> list =new ArrayList<Boys>();
while (rs.next()){
Boys boys=new Boys();
boys.setId(rs.getInt("id"));
boys.setBoyNme(rs.getString("boyName"));
boys.setUserCP(rs.getInt("userCP"));
list.add(boys);
}
for (Boys boys : list) {
System.out.println(boys);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
if (conn!=null){
conn.close();
}
if (st!=null){
st.close();
}
if (rs!=null){
rs.close();
}
}
}
}
五、JDBC工具类
package cn.JDBC.Test;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @Author:张金贺
* @Date:2022/7/7 19:09
* @Version 1.0
*/
public class demo04 {
public static void main(String[] args) throws SQLException {
Connection conn =null;
Statement st =null;
ResultSet rs =null;
try {
conn = jdbcutil.getConn();
st = conn.createStatement();
rs = st.executeQuery("select * from boys ");
List<Boys> list =new ArrayList<Boys>();
while (rs.next()){
Boys boys=new Boys();
boys.setId(rs.getInt("id"));
boys.setBoyNme(rs.getString("boyName"));
boys.setUserCP(rs.getInt("userCP"));
list.add(boys);
}
for (Boys boys : list) {
System.out.println(boys);
}
} catch ( SQLException e) {
e.printStackTrace();
}finally {
jdbcutil.close(st,conn,rs);
}
}
}
package cn.JDBC.Test;
import java.sql.*;
/**
* @Author:张金贺
* @Date:2022/7/7 18:56
* @Version 1.0
*/
public class jdbcutil {
private static String url = "jdbc:mysql://localhost:3306/girls";
private static String user = "root";
private static String password = "root";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void close(Statement st, Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Statement st, Connection conn, ResultSet rs) {
close(st, conn);
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
六、登录功能的实现
package cn.JDBC.Test; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; /** * @Author:张金贺 * @Date:2022/7/7 19:17 * @Version 1.0 */ public class login { public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.println("请输入用户名"); String name=sc.nextLine(); System.out.println("请输入密码"); String pwd=sc.nextLine(); login(name,pwd); } public static void login (String name,String pwd){ Connection conn =null; Statement st =null; ResultSet rs =null; try { conn = jdbcutil.getConn(); st = conn.createStatement(); rs = st.executeQuery("select * from boys where boyName= '" + name + "'and userCP ='" + pwd + "'"); if (rs.next()){ System.out.println("登录成功"); }else { System.out.println("登录失败");} } catch (SQLException e) { e.printStackTrace(); }finally { jdbcutil.close(st,conn,rs); } } }
七、sql注入漏洞
select 语句结尾拼接 or 1=1!!!
PreparedStatement解决sql注入:
public static void login (String name,String pwd){ Connection conn =null; PreparedStatement st =null; ResultSet rs =null; try { conn = jdbcutil.getConn(); String sql="select * from boys where boyName= ? and userCP =?"; conn.prepareStatement(sql); st.setString(1,name); st.setString(2,pwd); rs = st.executeQuery();
八、JDBC事务处理
提交、回滚:关闭事物自动提交,也就是开启手动提交事物conn.setAutoCommit(false) ;执行成功提交事物conn. commit() ;执行失败回滚事物conn.rollback();
九、其他
1.c3p0数据库连接池
导入jar包:c3p0、数据库驱动
src根目录下放入:c3p0-config.xml并修改参数
//创建c3po对象 DataSource ds=new DataSource(); Connection conn=ds.getConnection();
2.druid数据库连接池
导入jar包:druid、数据库驱动
src根目录下放入:druid.properties并修改参数
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/test username=root password-=123456 initiasize=5 maxActive=10 maxWait=3000 public static void main(String[] args) { // 创建一个Properties集合 Properties pro =new Properties() ; pro.load(demo002.class.getClassLoader().getResourceAsStream("druid.properties")); //创建一个DataSource DataSource ds= DruidDataSourceFactory. createDatlasource(pro); Connection conn = ds.getConnectiono ; }
3.durid封装工具类案例
package cn.JDBC.Test;
import javax.sql.DataSource;
import javax.swing.plaf.nimbus.State;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Collections;
import java.util.Properties;
/**
* @Author:张金贺
* @Date:2022/7/7 20:17
* @Version 1.0
*/
public class d {
private static DataSource ds;
static {
Properties pro =new Properties() ;
pro.load(d.class.getClassLoader().getResourceAsStream("druid.properties"));
ds= DruidDataSourceFactory. createDatlasource(pro);
}
public static Connection getConnection(){
return ds.getConnection();
}
public static void close(Statement st,Connection conn){
if (st!=null){
st.close();
}if (conn!=null) {
conn.close();
}
}
public static void close(Statement st, Connection conn, ResultSet rs){
close(st,conn);
if(rs!=null){
rs.close();
}
}
}
public static void main(String[] args) throws Exception { //获取连接 Connection conn = Druidutil.getConnection(); PreparedStatement pst = conn.prepareStatement("insert into account(name,money) values(?,?)"); pst.setString(1,"小强"); int count = pst.executeUpdate(); System.out.println(count); Druidutil.close(pst, conn); }
4.jdbcTemplate
导入jar包:spring-beans、spring-core、spring-jdbc、spring-tx、commons-logging。
duridutil:
package cn.JDBC.Test;
import javax.sql.DataSource;
import javax.swing.plaf.nimbus.State;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Collections;
import java.util.Properties;
/**
* @Author:张金贺
* @Date:2022/7/7 20:17
* @Version 1.0
*/
public class d {
private static DataSource ds;
static {
Properties pro =new Properties() ;
pro.load(d.class.getClassLoader().getResourceAsStream("druid.properties"));
ds= DruidDataSourceFactory. createDatlasource(pro);
}
public static Connection getConnection(){
return ds.getConnection();
}
public static void close(Statement st,Connection conn){
if (st!=null){
st.close();
}if (conn!=null) {
conn.close();
}
}
public static void close(Statement st, Connection conn, ResultSet rs){
close(st,conn);
if(rs!=null){
rs.close();
}
}
public static DataSource getDataSource() {
return ds;
}
}
(1)jdbcTemplate插入数据
public static void main(String[] args) { //1.创建一个jdbcTemplate对象 JdbcTemplate jt= new JdbcTemplate(Druidutil.getDataSource() ) ; //2.执行sql语句 String sql = "insert into accouunt(id,name,money) values(null,?,?)"; int count = jt.update(sql,"小明",1000f); System. out.println(count); }
(2)jdbcTemplate修改删除
String sql = "sql语句";
(3)jdbcTemplate查询
创建pojo实体类
package cn.JDBC;
import org.junit.Test;
import java.util.Map;
/**
* @Author:张金贺
* @Date:2022/7/7 20:39
* @Version 1.0
*/
public class demo02 {
//1.创建一个jdbcTemplate对象
JdbcTemplate jt = new JdbcTemplate(Druidutil.getDataSource() );
@Test
public void Search1(){
Map<String,Object> map =jt.queryForMap("select from account where id=?",1);
System.out.println(map);
}
@Test
public void Search2(){
List<Account> lst = jt.query("select from account",new BeanPropertyRowMapper<Account>(Account.class);
for (Account account : lst){
System.out.println(account) ;
}
}
@Test
public void Search3(){
int count = jt.queryForobject("select count(*) from account", Integer.class);
System.out.println(count);
}
}
十、JDBC五种连接方式
边栏推荐
猜你喜欢
2022/08/02 学习笔记 (day22) 多线程
High availability, two locations and three centers
Detailed explanation of MOSN reverse channel
Harmony OS ets ArkUI 】 【 】 the development basic page layout and data connection
Talking about GIS Data (5) - Geographic Coordinate System
typescript45-接口之间的兼容性
数字孪生园区场景中的坐标知识
【Harmony OS】【ARK UI】Date 基本操作
Build your own web page on the Raspberry Pi (2)
Exception(异常) 和 Error(错误)区别解析
随机推荐
Build your own web page on raspberry pie (1)
私域流量引流方法?分享购火爆的商业模式,你值得拥有
接口测试框架实战(二)| 接口请求断言
Common fluorescent dyes to modify a variety of groups and its excitation and emission wavelength data in the data
1. 两数之和
1069 微博转发抽奖 (20 分)(C语言)
Peptides mediated PEG DSPE of phospholipids, targeted functional materials - PEG - RGD/TAT/NGR/APRPG
Common lipophilic cell membrane dyes DiO, Dil, DiR, Did spectrograms and experimental procedures
接口测试实战| GET/POST 请求区别详解
常见亲脂性细胞膜染料DiO, Dil, DiR, Did光谱图和实验操作流程
阿里云对象存储oss私有桶生成链接
设计模式——组合模式、享元模式(Integer缓存)(结构型模式)
typescript40-class类的保护修饰符
closures in js
接口测试框架实战(一) | Requests 与接口请求构造
VR全景展打造专属元宇宙观展空间
建立树形结构
typescript39-class类的可见修饰符
Get the Ip tool class
在树莓派上搭建属于自己的网页(2)