JDBC连接数据库

1 篇文章 0 订阅

JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JDBC_dome1 {
    public static void main(String[] args) throws Exception {

        //获取连接
      //  String url="jdbc:mysql://localhost:3306";
        String url="jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT&rewriteBatchedStatements=true";
        String username="root";
        String password="123456";
        Connection conn= DriverManager.getConnection(url,username,password);

        //定义Sql
        String sql="" +
                "create table 学生( " +
                "    姓名 char(10), " +
                "    编号 tinyint, " +
                "    地址 char(10)" +
                ");";

        //获取sql执行对象
        Statement stml = conn.createStatement();

        //执行sql
        int  counnt=stml.executeUpdate(sql);

        //处理结果
        System.out.println(counnt);

        //结束进程,释放资源
        stml.close();
        conn.close();

    }
}

image-20220307204055531

image-20220307223805943

// 创建一个自己的数据库
create database bjpwwoernode;
//使用bjpwoernode数据
use bjpwoernode;
//初始化数据
source 初始化数据的目录
代码实现

这是一个事务处理存在问题的程序

package com.itheima;

import java.sql.*;

public class JDBC_Account {
    public static String url="jdbc:mysql://localhost:3306/bjpowernode";
    public static String name="root";
    public static String passwd="123456";

    public static Connection conn=null;
    public static  PreparedStatement ps=null;
    public static ResultSet re=null;

    public static void main(String[] args) {
        String username=null;
        String account=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn= DriverManager.getConnection(url,name,passwd);
            String sql="update accout set balance=balance-? where username=?";
            ps=conn.prepareStatement(sql);
            ps.setDouble(1,1000);
            ps.setString(2,"卡卡罗特");
            int l=ps.executeUpdate();
            System.out.println(l);
            sql="update accout set balance=balance+? where username=?";
            ps=conn.prepareStatement(sql);
            ps.setDouble(1,1000);
            ps.setString(2,"贝吉塔");
            int i=ps.executeUpdate();
            System.out.println(i);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(re!=null){
                try {
                    re.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

JDBC的事务处理部分

conn.setAutoCommit(false) //修改为手动提交
conn.commit() //提交事务
coon.rollback() //出现异常数据回滚
代码的实现部分
package com.itheima;

import java.sql.*;

public class JDBC_Account {
    public static String url="jdbc:mysql://localhost:3306/bjpowernode";
    public static String name="root";
    public static String passwd="123456";

    public static Connection conn=null;
    public static  PreparedStatement ps=null;
    public static ResultSet re=null;

    public static void main(String[] args) {
        String username=null;
        String account=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn= DriverManager.getConnection(url,name,passwd);
            String sql="update accout set balance=balance-? where username=?";
            //设置数据的提交为手动的模式
            conn.setAutoCommit(false);

            ps=conn.prepareStatement(sql);
            ps.setDouble(1,1000);
            ps.setString(2,"卡卡罗特");
            int l=ps.executeUpdate();
            System.out.println(l);
            //如果这里的数据出现异常则这里后面的代码就不会执行,那么就会出现账户的余额丢失
     /*       String str=null;
            System.out.println(str.toString());*/

            sql="update accout set balance=balance+? where username=?";
            ps=conn.prepareStatement(sql);
            ps.setDouble(1,1000);
            ps.setString(2,"贝吉塔");
            int i=ps.executeUpdate();
            System.out.println(i);
            //执行完所有的业务之后进行数据的提交
            conn.commit();
        } catch (Exception e) {
            try {
                //如果出现了异常则需要在这里进行数据的回滚
                conn.rollback();

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        }finally{
            if(re!=null){
                try {
                    re.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
JDBC工具类
package com.itheima2;

import java.sql.*;

public class JDBCLoad {
    //私有化构造器,只能通过类名去调用方法
    private JDBCLoad(){};
    //因为调用的是同一个类所以,驱动的注册只需要一次即可
    static{
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //连接到数据库,因为在主程序中会进行异常的处理,所以getConnection方法中的异常处理需要上抛
    public static  Connection getConnection(String url) throws Exception{
        return DriverManager.getConnection(url,"root","123456");
    }
    //关闭资源
    public static void close(Connection conn, Statement st, ResultSet re){
        if(re!=null){
            try {
                re.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(st!=null){
            try {
               st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
测试代码
package com.itheima;

import com.itheima2.JDBCLoad;

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

public class JDBC_loadTest {
    public static PreparedStatement ps=null;
    public static ResultSet rs=null;
    public static Connection conn=null;
    public static void main(String[] args) {
        String str="jdbc:mysql://localhost:3306/bjpowernode";
        try {
            conn= JDBCLoad.getConnection(str);
            String sql="select * from emp where sal > ?";
            ps=conn.prepareStatement(sql);
            ps.setDouble(1,1500);
            rs=ps.executeQuery();
            while(rs.next()){
                System.out.println(rs.getString("ENAME"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JDBCLoad.close(conn,ps,rs);
        }
    }
}

image-20220309094219215

在查询诗句中的结尾加入 for update 在当前的事务中还没有结束的时候 该行的数据无法被其他的事务进行修改操作。(行集锁,悲观锁)

悲观锁: 事务必须排对执行,数据锁住无法执行。

乐观锁:数据可以允许被多个线程同时并发操作执行,只需要一个版本号

image-20220309095116103

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值