Java与MySQL数据库的连接

当今的软件开发中,数据库是不可或缺的组成部分之一。而MySQL作为一种流行的关系型数据库管理系统(RDBMS),在许多应用程序中广泛使用。本篇博客将介绍MySQL数据库的基本概念以及如何在实际项目中使用MySQL进行数据管理和操作。

什么是MySQL?

MySQL是一种开源的关系型数据库管理系统,由瑞典MySQL AB公司开发,目前由Oracle公司维护和支持。它是一种基于客户端-服务器模型的数据库系统,采用了SQL(Structured Query Language)作为其主要查询语言。MySQL以其稳定性、可靠性和性能而闻名,被广泛应用于Web开发、企业应用和嵌入式系统中。

MySQL的特性

  1. 开源免费:MySQL采用GNU通用公共许可证(GPL),可免费获取和使用。
  2. 跨平台:MySQL可在多种操作系统上运行,包括Windows、Linux、Mac OS等。
  3. 高性能:MySQL具有出色的性能,能够处理大规模数据和高并发请求。
  4. 灵活性:支持多种存储引擎,如InnoDB、MyISAM等,每种引擎都有不同的特点和适用场景。
  5. 安全性:提供数据加密、访问控制等安全特性,保障数据的机密性和完整性。
  6. 易用性:MySQL具有直观的管理界面和丰富的文档资源,便于开发人员快速上手和维护。

在项目中使用MySQL

接下来,我们将演示如何在一个简单的Python项目中使用MySQL数据库进行数据管理。假设我们正在开发一个博客系统,需要存储用户信息和文章内容。

首先,需要确保Java项目中包含了MySQL的驱动程序。可以将MySQL的JDBC驱动程序添加到项目中,或者使用Maven等构建工具管理依赖。

<!-- pom.xml -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.28</version>
</dependency>

接下来将演示如何在Java中连接MySQL数据库,并执行一些基本的数据库操作。

增删改查部分:

import java.sql.*;

public class MySQLExample {

    // JDBC连接信息
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/blog_db";
    static final String USER = "root";
    static final String PASS = "your_password";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册JDBC驱动
            Class.forName(JDBC_DRIVER);

            // 打开连接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询
            System.out.println("实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, username, email FROM users";
            ResultSet rs = stmt.executeQuery(sql);

            // 展开结果集数据库
            while (rs.next()) {
                // 通过字段检索
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String email = rs.getString("email");

                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 用户名: " + username);
                System.out.println(", 电子邮件: " + email);
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            // 处理JDBC错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理Class.forName错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

增:

  @Test
    public void testAdd() throws Exception {
        Random r = new Random(20);
        //接受页面提交的参数
        for(int i = 0 ;i<101;i++){
            int id = i + 1;
            String name = "张" + i ;
            int age = r.nextInt()+18;
            int score = r.nextInt()+80;
            //1.获取连接对像
            Properties prop = new Properties();
            prop.load(new FileInputStream("src/druid.properties"));
            DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
            Connection conn = dataSource.getConnection();
            //2.定义sql
            String sql = "insert into tb_brand(id,name,age,score) values(?,?,?,?)";
            //3.获取pstmt对象
            PreparedStatement pstmt = conn.prepareStatement(sql);
            //4.设置参数
            pstmt.setInt(1, id);
            pstmt.setString(2, name);
            pstmt.setInt(3, age);
            pstmt.setInt(4, score);
            //5.执行sql
            int count = pstmt.executeUpdate();
            //6.处理结果
            System.out.println(count > 0);

            //7.释放资源
            pstmt.close();
            conn.close();
        }

删:

 @Test
    public void testDrop() throws Exception {
        //接受页面提交的参数

        int id = 4;
        //1.获取连接对像
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        Connection conn = dataSource.getConnection();
        //2.定义sql
        String sql = "delete from tb_brand where id = ?";
        //3.获取pstmt对象
        PreparedStatement pstmt = conn.prepareStatement(sql);
        //4.设置参数
        pstmt.setInt(1, id);
        //5.执行sql
        int count = pstmt.executeUpdate();
        //6.处理结果
        System.out.println(count > 0);

        //7.释放资源
        pstmt.close();
        conn.close();
    }

 改:

@Test
    public void testUpdate() throws Exception {
         //接受页面提交的参数
         String brandName = "香飘飘";
         String companyName = "香飘飘";
         int ordered = 1000;
         String description = "绕地球三圈";
         int status = 1;
         int id = 4;

        //1.获取连接对像
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        Connection conn = dataSource.getConnection();
         //2.定义sql
         String sql = " update tb_brand \n" +
                 "      set brand_name = ?,\n" +
                 "          company_name = ?,\n" +
                 "          ordered  = ?,\n" +
                 "          description = ?,\n" +
                 "          status = ?\n" +
                 "      where id = ?";
         //3.获取pstmt对象
         PreparedStatement pstmt = conn.prepareStatement(sql);
         //4.设置参数
         pstmt.setString(1, brandName);
         pstmt.setString(2, companyName);
         pstmt.setInt(3, ordered);
         pstmt.setString(4, description);
         pstmt.setInt(5, status);
         pstmt.setInt(6,id);
         //5.执行sql
         int count = pstmt.executeUpdate();
         //6.处理结果
         System.out.println(count > 0);

         //7.释放资源
         pstmt.close();
         conn.close();
    }

查:

 @Test
    public void testSelectAll() throws Exception {
        //1.获取连接对像
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));

        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

        Connection conn = dataSource.getConnection();
        //2.定义sql
        String sql = "select * from tb_brand;";
        //3.获取pstmt对象
        PreparedStatement pstmt = conn.prepareStatement(sql);
        //4.设置参数
        //5.执行sql
        ResultSet rs = pstmt.executeQuery();
        //6.处理结果 List<Brand> 封装Brand对象,装载list集合
        Brand brand = null;
        List<Brand> brands = new ArrayList<>();
        while (rs.next()) {
            //获取数据
            int id = rs.getInt("id");
            String Name = rs.getString("name");
            int age = rs.getInt("age");
            int score = rs.getInt("score");
            //封装Brand对象
            brand = new Brand();
            brand.setId(id);
            brand.setBrandName(Name);
           // brand.setCompanyName(companyName);
            brand.setOrdered(age);
           // brand.setDescription(description);
            brand.setStatus(score);
            //装载集合
            brands.add(brand);
        }
        System.out.println(brands);
        //7.释放资源
        rs.close();
        pstmt.close();
        conn.close();
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值