首页 > 数据库 >数据库驱和JDBC

数据库驱和JDBC

时间:2022-12-20 14:34:21浏览次数:33  
标签:JDBC String rs 数据库 System st conn out

数据库驱动

  顾名思义,数据库驱动是应用程序和数据库存储之间的一种接口,数据库厂商为了某一种

开发语言环境(比如Java,C)能够实现数据库调用而开发的类似翻译员功能的程序,将复杂

的数据库操作与通信抽象成为了当前开发语言的访问接口。

 

JDBC

  SUN公司为了简化开发人员的操作,提供了一个(Java操作数据库)的规范,俗称JDBC。

这些规范的实现由具体的厂商去做~

  需要导入一个数据库驱动包,数据库什么版本就下什么版本,我们这里是5.1.47的驱动

 

第一个JDBC程序

    1.创建测试数据库

CREATE DATABASE jdbcStudy CHARACTER SET utf8 COLLATE utf8_general_ci;

USE jdbcStudy;

CREATE TABLE `users`(
 id INT PRIMARY KEY,
 NAME VARCHAR(40),
 PASSWORD VARCHAR(40),
 email VARCHAR(60),
 birthday DATE
);

INSERT INTO `users`(id,NAME,PASSWORD,email,birthday)
VALUES(1,'zhansan','123456','[email protected]','1980-12-04'),
(2,'lisi','123456','[email protected]','1981-12-04'),
(3,'wangwu','123456','[email protected]','1979-12-04')

  2.创建一个普通项目

  3.导入数据库驱动

  新建lib文件夹,将驱动的jar包放进去,并add library

  

 

   4.编写测试代码

//我的第一个JDBC程序
public class jdbcFirstDemo {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");//固定写法
        //2.用户信息
        String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
        String userName="root";
        String password="123456";
        //3.连接成功,数据库对象,代表数据库
        Connection connection = DriverManager.getConnection(url, userName, password);
        //4.执行SQL的对象
        Statement statement = connection.createStatement();
        //5.执行SQL
        String sql="select * from users";
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
            System.out.println("id="+resultSet.getObject("id"));
            System.out.println("name="+resultSet.getObject("NAME"));
            System.out.println("pwd="+resultSet.getObject("PASSWORD"));
            System.out.println("email="+resultSet.getObject("email"));
            System.out.println("birth="+resultSet.getObject("birthday"));
            System.out.println("==============================");
        }
        //6.释放连接
        resultSet.close();
        statement.close();
        connection.close();
    }
}

 

statement对象

  JDBC中statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库

发送增删改查语句即可。

  statement对象的executeUpdate方法,用于向数据库发送增删改的SQL语句,executeUpdate执行完成后,将会返回

一个整数(即增删改语句导致了数据库j几行数据发生了变化)

  statement对象的executeQuery方法,用于向数据库发送查询语句,executeQuery方法返回代表查询结果的resultSet对象

1.CRUD操作-insert

Statement st = conn.createStatement();
String sql = "insert into user(...) values(...)";
int num = st.executeUpdate(sql);
if(num > 0){
    System.out.println("插入成功!");
}

2.CRUD操作-delete

Statement st = conn.createStatement();
String sql = "delete from user where id=1";
int num = st.executeUpdate(sql);
if(num > 0){
    System.out.println("删除成功!");
}

3.CRUD操作-update

Statement st = conn.createStatement();
String sql = "update user set name = '..' where name = '..';
int num = st.executeUpdate(sql);
if(num > 0){
    System.out.println("修改成功!");
}

4.CRUD操作-select

Statement st = conn.createStatement();
String sql = "select * from user where id = 1";
ResultSet rs = st.executeQuery(sql);
while(rs.next){
    System.out.println(rs.getObject("id"));
    ....
}

提取工具类

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 in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(in);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            //1.加载驱动只用加载一次
            Class.forName(driver);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() throws SQLException {
       return DriverManager.getConnection(url,username,password);
    }
    //释放资源
    public static void release(Connection conn, Statement st, ResultSet rs){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (rs!=null){
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

INSERT

public class TestInsert {
    public static void main(String[] args) {
        Connection conn = null;
        Statement st =null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();//获取数据库连接
            st = conn.createStatement();
            String  sql = "insert into users(id,`NAME`,`PASSWORD`,`email`,birthday)"+
                            "values(4,'xiaolei','33312','[email protected]','2022-02-02')";
            int i = st.executeUpdate(sql);
            if (i>0){
                System.out.println("插入成功!!!");
            }
        } catch (SQLException e) {
             e.printStackTrace();
        }finally {
            JdbcUtils.release(conn,st,rs);
        }
    }
}

UPDATE

public class TestUpdate {
    public static void main(String[] args) {
        Connection conn = null;
        Statement st = null;
        ResultSet rs= null;
        try {
            conn = JdbcUtils.getConnection();
            st = conn.createStatement();
            String sql = "update users set name = '憨憨' where name = 'wangwu'";
            int i = st.executeUpdate(sql);
            if (i>0){
                System.out.println("更新成功!!!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn,st,rs);
        }
    }
}

DELETE

public class TestDelete {
    public static void main(String[] args) {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            st = conn.createStatement();
            String sql = "delete from users where id =4";
            int i = st.executeUpdate(sql);
            if (i>0){
                System.out.println("删除成功!!!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn,st,rs);
        }
    }
}

SELECT

public class TestSelect {
    public static void main(String[] args) {
        Connection conn = null;
        Statement st= null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            st = conn.createStatement();
            String sql = "select * from users";
            rs = st.executeQuery(sql);
            while (rs.next()){
                System.out.println("id="+rs.getObject("id"));
                System.out.println("name="+rs.getObject("NAME"));
                System.out.println("password="+rs.getObject("PASSWORD"));
                System.out.println("email="+rs.getObject("email"));
                System.out.println("birthday="+rs.getObject("birthday"));
                System.out.println("+++++++++++++++++++++++");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn,st,rs);
        }
    }
}

 

 

标签:JDBC,String,rs,数据库,System,st,conn,out
From: https://www.cnblogs.com/zhulei118/p/16992209.html

相关文章

  • 使用peewee模块操作数据库
    1.简介Peewee是一个PythonORM(Object-RelationalMapping)库,支持SQLite、MySQL、PostgreSQL和Cockroach数据库。在ORM系统中,每个类都映射到底层数据库中的一个表......
  • 达梦数据库修改最大连接数
    达梦数据库安装默认连接数为100,实际开发中能不够用,如下是修改最大连接数的方法1、查看最大连接数:selectSF_GET_PARA_VALUE(2,'MAX_SESSIONS');#结果100 2、修改最......
  • 数据库性能优化小结
    近期部门有大牛分享了下数据库的相关知识,自己这里趁热也总结一下对应测试来说比较容易涉及到的性能优化方面的知识。数据库的性能从宏观上可以分为:查询、插入;这里小结了下影......
  • 使用 expdp导入导出oracle 数据库
    expdp用户名/密码@afspdbTABLES=table1dumpfile=/yfq/expdp_a11.dmp(1)执行之后报错了;expdp TNScouldnotresolvetheconnectidentifierspecified查了下是......
  • mongodb数据库修复 mongodb数据库丢失恢复 mongodb数据库数据恢复 mongodb数据库文件0
    mongodb数据库修复mongodb数据库丢失恢复mongodb数据库数据恢复mongodb数据库文件0kb数据恢复客户名称保密数据类型mongodb3.0数据容量20GB故障类型强制重启服务器......
  • IDEA连接数据库
    在入门案例映射配置文件中存在报红的情况。问题如下:产生的原因:Idea和数据库没有建立连接,不识别表信息。但是大家一定要记住,它并不影响程序的执行。解决方式:在Idea中配......
  • 实现 .Net 7 下的数据库定时检查
    在软件开发过程中,有时候我们需要定时地检查数据库中的数据,并在发现新增数据时触发一个动作。为了实现这个需求,我们在.Net7下进行一次简单的演示。PeriodicTimer.Net6......
  • DataGrip导出数据库sql文件
    选中一个数据库中指定数据表,然后单击右键,选择Exportwithmysqldump如果显示如图所示错误(路径不存在),则在终端里输入whichmysqldump,然后去替代默认路径即可。......
  • JDBC之ResultSet和元数据
    ResultSet从名字上就可以看到是结果集,表示的是查询出来的结果集。JDBC用ResultSet来封装结果集,查询结果表的对象。查询结果分为两种情况:单值单个结果,比如说SQL如下:s......
  • 如何搭建一个数据库服务器平台
    玩Oracle2年多了,从接触Oracle 到现在,一直没有停止过学习。 要学的东西太多,刚入门的时候是这样的感觉,现在还是这样的感觉。 有时候也在想,还要学多长时间才能感觉自我良好......