JDBC访问数据库

命令行使用SQL语句

首先启动MySQL

MySQL -h localhost -u root -p123456

依次输入

1.create database xsxx

2.use xsxx;

3.create table xs(

id int(6) not null primary key,

name char(10) not null,

major char(20) not null);

4.insert into xs values(520,'dan','英语');

然后我们在输入select name,major from xs where id = 520;查询创建的表

现在我们已经创建了一个表

接下来编写一个使用后台数据库为MySQL的JDBC程序。

1.引入JDBC驱动程序

找到你文件夹中的mysql-connector-java

添加成功后会有一个外部库

现在编写JDBC程序,使用已创建的xsxx数据库和其中的xs表

package com.company.jdbc;

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

public class JDBC {
    public static void main(String[] args){
        ResultSet rs = null;
        Statement stmt = null;
        Connection conn = null;
        try{
            /*
            加载并注册Mysql的jdbc驱动
             */
            Class.forName("com.mysql.jdbc.Driver");
            /*
            建立到mysql数据库的连接
             */
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/xsxx","root","123456"
            );
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from xs");
            while(rs.next()){
                System.out.print(rs.getInt("id"));
                System.out.print(rs.getString("name"));
                System.out.print(rs.getString("major"));

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            try{
                if(rs != null){
                    rs.close();//关闭ResultSet对象
                    rs = null;
                }
                if(stmt!=null){
                    stmt.close();
                    stmt = null;
                }
                if(conn!=null){
                    conn.close();
                    conn = null;
                }
            }catch(SQLException e){
                e.printStackTrace();
            }
        }

    }
}

 

成功输出xs表中的信息。

向数据库xsxx中的xs表中添加记录、修改记录、删除记录。

package com.company.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/*
向数据库xsxx中的xs表中添加记录、修改记录、删除记录
 */
public class DML {
    public static void main(String[] args){
        ResultSet rs = null;
        Statement stmt = null;
        Connection conn = null;

        try{
             /*
            加载并注册Mysql的jdbc驱动
             */
            Class.forName("com.mysql.jdbc.Driver");
            /*
            建立到mysql数据库的连接
             */
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/xsxx","root","123456"
            );
            stmt = conn.createStatement();

            /* 添加记录 */
            System.out.println("添加后:");
            String sql1="insert into xs values (123,'jun','计算机');";
            stmt.executeUpdate(sql1);
            rs = stmt.executeQuery("select * from xs");
            while(rs.next()){
                System.out.println(rs.getInt("id"));
                System.out.println(rs.getString("name"));
                System.out.println(rs.getString("major"));
            }
            /*
            修改数据
             */
            System.out.println("修改数据后:");
            String sql2="update xs set name = '牛马' where id=123;";
            stmt.executeUpdate(sql2);
            rs = stmt.executeQuery("select * from xs");
            while(rs.next()){
                System.out.println(rs.getInt("id"));
                System.out.println(rs.getString("name"));
                System.out.println(rs.getString("major"));
            }
            /*
            删除数据
             */
            System.out.println("删除数据后:");
            String sql3="delete from xs where id = 123;";
            stmt.executeUpdate(sql3);
            rs = stmt.executeQuery("select * from xs");
            while(rs.next()){
                System.out.println(rs.getInt("id"));
                System.out.println(rs.getString("name"));
                System.out.println(rs.getString("major"));
            }


        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            try{
                if(rs != null){
                    rs.close();//关闭ResultSet对象
                    rs = null;
                }
                if(stmt!=null){
                    stmt.close();
                    stmt = null;
                }
                if(conn!=null){
                    conn.close();
                    conn = null;
                }
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }
}

 代码是没有问题的,这里我发现如果表中已存在的数据没有删除的话你再次运行就会报错但是返回值为0。

小发现或者说是基础没打好:

System.out.print();

System.out.println();

这两句是不一样的,前者不会自动换行,后者会输出换行符。

调整代码后:

 更加好的阅读到运行结果。

PreparedStatement对象和Statement对象的区别;一般是多次执行SQL语句就使用PreparedStatement,单次执行就使用Statement。

这里使用PreparedStatement对象对xsxx数据库中的xs表添加记录。

package com.company.jdbc;

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

public class TestPreparedStatement {
    public static void main(String[] args){
        ResultSet rs = null;
        Statement stmt = null;
        Connection conn = null;
        PreparedStatement pstmt = null;
        try{
            /*
            加载并注册Mysql的jdbc驱动
             */
            Class.forName("com.mysql.jdbc.Driver");
            /*
            建立到mysql数据库的连接
             */
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/xsxx","root","123456"
            );
            //访问数据库,执行SQL语句
            stmt = conn.createStatement();
            pstmt = conn.prepareStatement("insert into xs values(?,?,?)");
            /*模板
            pstmt.setInt(1,1);
            pstmt.setString(2,"彭于晏");
            pstmt.setString(3,"化学工艺");
            pstmt.executeUpdate();
             */
            //添加第一条记录
            pstmt.setInt(1,1);
            pstmt.setString(2,"彭于晏");
            pstmt.setString(3,"化学工艺");
            pstmt.executeUpdate();
            //添加第二条记录
            pstmt.setInt(1,2);
            pstmt.setString(2,"小李子");
            pstmt.setString(3,"环境科学");
            pstmt.executeUpdate();
            //添加第三条记录
            pstmt.setInt(1,3);
            pstmt.setString(2,"梅西");
            pstmt.setString(3,"车辆工程");
            pstmt.executeUpdate();

            rs = stmt.executeQuery("select * from xs");//查询表中的所有数据
            while(rs.next()){
                System.out.print(rs.getInt("id"));
                System.out.print(rs.getString("name"));
                System.out.println(rs.getString("major"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e){
            e.printStackTrace();
        }finally{
            try{
                if(rs != null){
                    rs.close();//释放资源,关闭ResultSet对象
                    rs = null;
                }
                if(pstmt != null){
                    pstmt.close();//释放资源,关闭PreparedStatement对象
                    pstmt = null;
                }
                if(stmt != null){
                    stmt.close();//释放资源,关闭Statement对象
                    stmt = null;
                }
                if(conn != null){
                    conn.close();//释放资源,关闭Connection对象
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

批处理(你将关联的SQL语句组合成一个批处理,并将他们当成一个调用提交给数据库。

当你一次发送多个SQL语句到数据库时,可以减少通信的资源消耗,从而提高性能)

JDBC Statement对象

我们实现了数据库的连接后就可以和数据库进行交互

 executeBatch()方法用于启动执行所有组合在一起的语句。

package com.company.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
public class TestBatch {
    public static void main(String[] args){
        ResultSet rs = null;
        Statement stmt = null;
        Connection conn = null;
        PreparedStatement pstmt = null;
        try{
            /*
            加载并注册Mysql的jdbc驱动
             */
            Class.forName("com.mysql.jdbc.Driver");
            /*
            建立到mysql数据库的连接
             */
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/xsxx","root","123456"
            );
            /*访问数据库,执行SQL语句*/
            pstmt = conn.prepareStatement("insert into xs values(?,?,?)");
            pstmt.setInt(1,4);
            pstmt.setString(2,"C罗");
            pstmt.setString(3,"光学");
            pstmt.addBatch();//加一条SQL语句
            pstmt.setInt(1,5);
            pstmt.setString(2,"内马尔");
            pstmt.setString(3,"电工理论");
            pstmt.addBatch();//加一条SQL语句
            pstmt.executeBatch();//批量更新
            stmt=conn.createStatement();

             

            rs = stmt.executeQuery("select * from xs");//查询表中的所有数据
            while(rs.next()){
                System.out.print(rs.getInt("id"));
                System.out.print(rs.getString("name"));
                System.out.println(rs.getString("major"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException e) {
            e.printStackTrace();
        }finally{
            try{
                if(rs != null){
                    rs.close();//释放资源,关闭ResultSet对象
                    rs = null;
                }
                if(pstmt != null){
                    pstmt.close();//释放资源,关闭PreparedStatement对象
                    pstmt = null;
                }
                if(stmt != null){
                    stmt.close();//释放资源,关闭Statement对象
                    stmt = null;
                }
                if(conn != null){
                    conn.close();//释放资源,关闭Connection对象
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
}

 事务处理

当一个连接对象被创建时,默认情况会被设置为自动提交,即每次成功执行一条SQL语句就会自动调用commit()方法向数据库提交,且不会回滚(“回滚(Rollback)指的是程序或数据处理错误,将程序或数据恢复到上一次正确状态的行为。回滚包括程序回滚和数据回滚等类型。”)。 为了将多余SQL语句作为一个事务执行,可以设置Connection对象的setAutoCommit(false)。然后在SQl语句执行后调用Connection对象的commit()方法来提交事务。或者在执行错误时用rollback()方法来回滚事务。

使用事务处理功能并使用JDBC的批处理向xsxx数据库中的xs表添加数据。

package com.company.jdbc;


import java.sql.*;

public class TestTransaction {
    public static void main(String[] args){
        ResultSet rs = null;
        Statement stmt = null;
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            /*
            加载并注册Mysql的jdbc驱动
             */
            Class.forName("com.mysql.jdbc.Driver");
            /*
            建立到mysql数据库的连接
             */
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/xsxx", "root", "123456"
            );
            conn.setAutoCommit(false);//禁用自动提交
            /*
            访问数据库,执行SQL语句
             */
            stmt = conn.createStatement();
            stmt.addBatch("insert into xs values(6,'川普','懂王')");
            stmt.addBatch("insert into xs values(7,'克里斯','通信工程')");
            stmt.addBatch("insert into xs values(8,'奥斯瓦尔多','临床医学')");
            stmt.addBatch("insert into xs values(9,'刀疤仔','生物医学')");
            stmt.addBatch("insert into xs values(10,'贝克汉姆','控制工程')");
            stmt.executeBatch();//提交一批命令
            conn.commit();
            conn.setAutoCommit(true);//开启自动提交

            rs = stmt.executeQuery("select * from xs");//查询表中的所有数据
            while(rs.next()){
                System.out.print(rs.getInt("id"));
                System.out.print(rs.getString("name"));
                System.out.println(rs.getString("major"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            try{
                if(rs != null){
                    rs.close();//释放资源,关闭ResultSet对象
                    rs = null;
                }
                if(pstmt != null){
                    pstmt.close();//释放资源,关闭PreparedStatement对象
                    pstmt = null;
                }
                if(stmt != null){
                    stmt.close();//释放资源,关闭Statement对象
                    stmt = null;
                }
                if(conn != null){
                    conn.close();//释放资源,关闭Connection对象
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值