TestNG - java连接mysql并查询数据

一、前言

  参考博客:https://blog.csdn.net/u013421629/article/details/78883991

二、idea的maven加载驱动

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>

三、java操作mysql代码

package com.tech.config;

import java.sql.*;

/**
 * @author 一加一
 * @data 2022/1/10 14:07
 */

public class testsql {
    public static void main(String[] args) {
        Connection con;
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://19.1.0.20:3306/mand?useUnicode=true&characterEncoding=utf-8&&useSSL=false";
        String user = "dev";
        String password = "OcC&=3a";
        try{
            Class.forName(driver);
            con= DriverManager.getConnection(url,user,password);
            if(!con.isClosed()){
                System.out.println("数据库连接成功");
            }
            Statement statement = con.createStatement();
            //执行查询语句
            String sql = "select * from dtask";
            ResultSet resultSet = statement.executeQuery(sql);
            //打印查询出来的东西
            String code;
            String region_name;
            while (resultSet.next()){
                code = resultSet.getString("code");
                region_name = resultSet.getString("region_name");
                System.out.println(code+'\t'+region_name);
            }
            //关闭连接
            resultSet.close();
            con.close();
            System.out.println("数据库连接已关闭");

        }catch (ClassNotFoundException e){
            System.out.println("数据库驱动没有安装");
        }catch (SQLException e){
            System.out.println("数据库连接失败");
        }
    }
}

 

四、运行结果

TestNG - java连接mysql并查询数据

五、贴上其他用法

TestNG - java连接mysql并查询数据

 

上一篇:PolarDB-X 存储架构之“基于Paxos的最佳生产实践”


下一篇:技术解读 | PolarDB-X 强一致分布式事务