jdbc连接MySql数据库

jdbc连接MySql数据库


package com.zhy;


import com.mysql.jdbc.Driver;

import java.sql.*;

/**
 * @author ZHY
 * @data 2021/2/15
 */
public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //0、配置信息
        //jdbc:mysql://localhost:3306/数据库? user=root & password= & useUnicode=true&characterEncoding=gbk 字符编码要加 & autoReconnect=true & failOverReadOnly=false
        String url = "jdbc:mysql://localhost:3306/testjdbc?useUnicode=true&characterEncoding=utf-8";
        String use = "root";
        String password = "123456";//不建议
        //1、加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2、链接数据库
        Connection cn = DriverManager.getConnection(url,use,password);
        //3、创建发送sql对象Statement crud 不安全
        Statement st = cn.createStatement();
        //4、编写sql
        String sql = "select * from users";
        //5、执行查询sql 返回一个 ResultSet 结果集
        ResultSet rs = st.executeQuery(sql);
        //5.1 遍历结果
        while (rs.next()){
            System.out.println("id = "+rs.getObject("id"));
            System.out.println("name = "+rs.getObject("name"));
            System.out.println("email = "+rs.getObject("email"));
            System.out.println("birthday = "+rs.getObject("birthday"));
        }
        //6、关闭连接 释放资源
        rs.close();
        st.close();
        cn.close();
    }
}

jdbc连接MySql数据库

上一篇:ORA-01219: 数据库或可插入数据库未打开: 仅允许在固定表或视图中查询 oracle


下一篇:nginx教程五,用GoAccess工具实时查看nginx日志