栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JDBC学习笔记

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JDBC学习笔记

01.什么是JDBC

Java DataBase Connectivity(Java语言连接数据库)

02.JDBC的本质是什么?
    JDBC是SUN公司制定的一套接口(interface)
        java.sql.*; (这个软件包下有很多接口。)

03.JDBC编程六步(需要背会)
    
    第一步:注册驱动(作用:告诉Java程序,即将要连接的是哪个品牌的数据库)

    第二步:获取连接(表示JVM的进程和数据库进程之间的通道打开了,这属于进程之间的通信,重量级的,使用完之后一定要关闭通道。)

    第三步:获取数据库操作对象(专门执行sql语句的对象)

    第四步:执行SQL语句(DQL DML....)

    第五步:处理查询结果集(只有当第四步执行的是select语句的时候,才有这第五步处理查询结果集。)

    第六步:释放资源(使用完资源之后一定要关闭资源。Java和数据库属于进程间的通信,开启之后一定要关闭。)

04.第一个jdbc程序

public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //导入驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //用户信息和url
        String url = "jdbc:mysql://localhost:3306/school?serverTimezone=UTC";
        String username="root";
        String password="123456789";
        //连接成功 数据库对象 connection代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //执行sql对象
        Statement statement = connection.createStatement();
        String sql = "select * from subject";
        //返回结果集
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
            System.out.println("subjectno"+resultSet.getObject("subjectno"));
            System.out.println("subjectname"+resultSet.getObject("subjectname"));
            System.out.println("classhour"+resultSet.getObject("classhour"));
            System.out.println("gradeid"+resultSet.getObject("gradeid"));
            System.out.println("====================");
        }

        //关闭连接
        resultSet.close();
        statement.close();
        connection.close();

    }
}

05.封装jdbc工具类

package lession1;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
    private static String driver=null;
    private static String url=null;
    private static String username=null;
    private static String password=null;
    static {
        try {
            InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(inputStream);//读取配置文件

            //获取文件中的值
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            //驱动只用一次
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }

    }
    //获取连接
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,username,password);
    }
    //关闭连接
    public void release(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
 Statement对象

Delete 

package lession1;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestDelete {
    public static void main(String[] args) {
        Connection connection=null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();
            statement=connection.createStatement();
            String sql = "delete from student where id=3";
            int i = statement.executeUpdate(sql);//返回一个影响行数
            if (i>0){
                System.out.println("删除成功");
            }else {
                System.out.println("删除失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,statement,resultSet);
        }
    }
}
Insert
package lession1;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestInsert {
    public static void main(String[] args) {
        Connection connection=null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();
            statement=connection.createStatement();
            String sql = "insert into student values(3,'张三','677887','男','2002-08-09')";
            int i = statement.executeUpdate(sql);
            if (i>0){
                System.out.println("增加成功");
            }else {
                System.out.println("增加失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,statement,resultSet);
        }
    }
}
 Update
package lession1;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestUpdate {
    public static void main(String[] args) {
        Connection connection=null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();
            statement=connection.createStatement();
            String sql = "update student set name='eleven',pwd='789879' where id=1";
            int i = statement.executeUpdate(sql);
            if (i>0){
                System.out.println("修改成功");
            }else {
                System.out.println("修改失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,statement,resultSet);
        }
    }
}
 Select
package lession1;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class TestSelect {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();
            statement = connection.createStatement();
            String sql = "select * from student where id=1";
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                System.out.println(resultSet.getString("name"));
                System.out.println(resultSet.getString("pwd"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,statement,resultSet);
        }
    }
}

 SQL注入问题

package lession1;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestSQL {
    public static void main(String[] args) {
        login("'or' 1=1","'or' 1=1");
    }
    public static void login(String username,String pwd){
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();
            statement = connection.createStatement();
            String sql = "select * from student where `name`='"+username+"'and `pwd`='"+pwd+"'";
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                System.out.println(resultSet.getString("name"));
                System.out.println(resultSet.getString("pwd"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,statement,resultSet);
        }
    }
}
PreparedStatement对象

Select

package lession2;

import lession1.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestSelect {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            connection = JdbcUtils.getConnection();
            String sql = "select * from student where id=?";
            statement = connection.prepareStatement(sql);//预编译
            statement.setInt(1,1);//手动设置参数
            resultSet = statement.executeQuery();//执行

            while (resultSet.next()){
                System.out.println(resultSet.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,statement,resultSet);
        }
    }
}

 Insert

package lession2;

import lession1.JdbcUtils;

import java.sql.*;

public class TestInsert {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();

            String sql = "insert into student values(?,?,?,?,?)";

            statement = connection.prepareStatement(sql);//预编译

            statement.setInt(1,3);
            statement.setString(2,"eleven");
            statement.setString(3,"6787987");
            statement.setString(4,"女");
            statement.setDate(5,new Date(new java.util.Date().getTime()));

            int i = statement.executeUpdate();//执行
            if (i>0){
                System.out.println("插入成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,statement,resultSet);
        }
    }
}

Update

package lession2;

import lession1.JdbcUtils;

import java.sql.*;

public class TestUpdate {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();

            String sql = "update student set name = ? where id=?";

            statement = connection.prepareStatement(sql);//预编译

            statement.setString(1,"wangwu");
            statement.setInt(2,4);

            int i = statement.executeUpdate();//执行
            if (i>0){
                System.out.println("修改成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,statement,resultSet);
        }
    }
}

Delete

package lession2;

import lession1.JdbcUtils;

import java.sql.*;

public class TestDelete {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();

            String sql = "delete from student where id=? ;";

            statement = connection.prepareStatement(sql);//预编译

            statement.setInt(1,4);

            int i = statement.executeUpdate();//执行
            if (i>0){
                System.out.println("删除成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,statement,resultSet);
        }
    }
}

数据库连接池

DBCP

需要引入的jar包

commons-dbcp-1.4.jar    commons-pool-1.6.jar

DBCP的配置文件

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123456

#
initialSize=10

#最大连接数量
maxActive=50

#
maxIdle=20

#
minIdle=5

#
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:【属性名=property;】
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF8

#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true

#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=

#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED

封装dbcp工具类

package lession3;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils_DBCP {
    private static DataSource dataSource=null;
    static {
        try {
            InputStream inputStream = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties properties = new Properties();
            properties.load(inputStream);//读取配置文件

            //创建数据源 工厂模式
            dataSource = BasicDataSourceFactory.createDataSource(properties);//和普通类的区别

        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }

    }
    //获取连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    //关闭连接
    public static void release(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

测试代码

package lession3;

import java.sql.*;

public class TestDbcp {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils_DBCP.getConnection();
            String sql = "insert into student values (?,?,?,?,?)";
            statement = connection.prepareStatement(sql);//预编译

            statement.setInt(1,4);
            statement.setString(2,"eleven");
            statement.setString(3,"6787987");
            statement.setString(4,"女");
            statement.setDate(5,new Date(new java.util.Date().getTime()));

            int i = statement.executeUpdate();//执行
            if (i>0){
                System.out.println("插入成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils_DBCP.release(connection,statement,resultSet);
        }
    }
}

C3P0

需要引入的jar包

c3p0-0.9.5.3.jar      mchange-commons-java-0.2.15.jar

c3p0的配置文件  

友友们,一定要记住xml文件最好放在src文件夹下面

最最最重要的是配置文件名字一定要是c3p0-config.xml

就是因为这个名字俺的数据库一直连接失败,搞了几个小时



    
    
        root
        123456789
        jdbc:mysql://localhost:3306/mm?serverTimezone=UTC
        com.mysql.cj.jdbc.Driver
        30000
        30
        3
        30
        100
        2
        200
    
    
    
        root
        123456789
        jdbc:mysql://localhost:3306/mm?serverTimezone=UTC
        com.mysql.cj.jdbc.Driver
        
        5
        
        20
        
        25
        
        5
    

封装c3p0的工具类

package lession3;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.*;

public class JdbcUtils_C3P0 {
    private static DataSource dataSource=null;
    static {
        try {
            dataSource = new ComboPooledDataSource();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }

    }
    //获取连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    //关闭连接
    public static void release(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

测试代码

package lession3;

import java.sql.*;

public class TestC3P0 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils_C3P0.getConnection();
            String sql = "insert into student values (?,?,?,?,?)";
            statement = connection.prepareStatement(sql);//预编译

            statement.setInt(1,5);
            statement.setString(2,"eleven");
            statement.setString(3,"6787987");
            statement.setString(4,"女");
            statement.setDate(5,new Date(new java.util.Date().getTime()));

            int i = statement.executeUpdate();//执行
            if (i>0){
                System.out.println("插入成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils_C3P0.release(connection,statement,resultSet);
        }
    }
}

JDBC事务

package lession3;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestTransaction {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        
        try {
            connection = JdbcUtils_C3P0.getConnection();

            //关闭自动提交 但他默认设置了关闭自动提交就开启事务
            connection.setAutoCommit(false);//开启事务
            String sql1 = "update transaction set money =money-200  where name='A'";
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();

            String sql2 = "update transaction set money =money+200  where name='B'";
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();

            //业务完毕,提交事务
            connection.commit();
            System.out.println("成功");
        } catch (SQLException e) {
            //回滚事务手动设置 默认事务会回滚
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            JdbcUtils_C3P0.release(connection,preparedStatement,resultSet);
        }
    }
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1029011.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号