idea通过jdbc连接数据库并导出数据

注:以导出下面这个表单(在student_information库中的danzi表)为例

1.创建一个简单的maven项目 2.导包(mysql)

<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
    </dependencies>

3.idea连接到数据库 尝试连接,若显示success则成功

注:若这里连接显示不成功(密码和账号确保输入正确的前提下),在下图属性栏中加上Asia/Shanghai,在去点击尝试连接即可

再导入对应的库(我这里是student_information)

4.JDBC固定步骤

public class Testjdbc {
          
   
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
          
   
        //配置信息
        String url="jdbc:mysql://localhost:3306/student_information?useUnicode=true&characterEncoding=utf-8";
        String username="root";
        String password="dd1234567899";
        //1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //3.向数据库发送SQL的对象
        Statement statement = connection.createStatement();
        //4.编写SQL
        String sql="select * from danzi";
        //5.执行查询SQL,返回一个ResultSet
        ResultSet rs = statement.executeQuery(sql);

        while (rs.next()){
          
   
            System.out.println("type="+rs.getObject("type"));
            System.out.println("time="+rs.getObject("time"));
            System.out.println("area="+rs.getObject("area"));
            System.out.println("money="+rs.getObject("money"));
            System.out.println("another="+rs.getObject("another"));
        }
        //6.关闭连接,释放资源
        rs.close();
        statement.close();
        connection.close();
    }
}

注:在执行sql一步中

    statement.executeQuery(sql) 执行查询sql语句 statement.execute(sql) 执行任何sql语句 statement.executeUpdate(sql) 执行跟新、插入、删除等sql语句 5.运行 导出成功。
经验分享 程序员 微信小程序 职场和发展