jdbc连接mysql数据库

package com.yibai.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;


public class JDBCTest {
     public static void main(String[] args) {
        String sql="select * from tbl_user";
        Connection conn=null;//连接
        Statement st = null;//创造执行sql
        ResultSet rs = null;//执行sql,返回结果
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","123456");
            st = conn.createStatement();
            rs = st.executeQuery(sql);
            
            while (rs.next()) {
                System.out.print(rs.getInt("id") + "  ");
                System.out.print(rs.getString("name") + "  ");
                System.out.print(rs.getString("password") + "  ");
                System.out.print(rs.getString("email") + "  ");
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }
            try {
                st.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }
            try {
                conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
     }
}

搭配方法
1. jdk7+老版5.0驱动com/mysql/jdbc/Driver
2. jdk8+新版6.0驱动com/mysql/cj/jdbc/Driver(现在已经更新到了8.0)
注意事项
1. 如果使用高版本的包,无论import还是在配置文件中配置驱动,都需要使用路径com/mysql/cj/jdbc/Driver,并且会有一些参数要求,比如必须加上选项 (?时区=“XXX”)等。
例如
       jdbc.url=jdbc:mysql://localhost:3306/servicesoftware?serverTimezone=UTC&useSSL=false
2. 很多框架不支持高版本mysql,所以如果报错请替换为低版本的包
jdbc下载地址:https://downloads.mysql.com/archives/c-j/

posted @ 2019-02-22 14:56  世人皆萌  阅读(272)  评论(0编辑  收藏  举报