JDBC链接MySql

来源:互联网 发布:ubuntu睡眠后无法唤醒 编辑:程序博客网 时间:2024/04/29 13:56

虽然是一百度就能搜到一大堆关于JDBC怎么链接但是我还是坚持手动去写一遍,然后用自己的方式记录下学习的过程,毕竟这是给自己记录的过程。

首先附 网站的下载链接
http://dev.mysql.com/downloads/connector/j/[这里写链接内容]

这里写图片描述

这里下载那个都行只是压缩的方式不同罢了
载完记得导入jar包

使用加载
第一步:
加载jdbc驱动类

        try{            //加载MySql的驱动类            Class.forName("com.mysql.jdbc.Driver") ;        }catch(ClassNotFoundException e){            System.out.println("找不到驱动程序类 ,加载驱动失败!");            e.printStackTrace() ;        }

第二步 创建数据库链接:

       Connection con = null;        try{            con = DriverManager.getConnection(url , username , password ) ;        }catch(SQLException se){            System.out.println("数据库连接失败!");            se.printStackTrace() ;        }

第三步创建声明:

/ 要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3
// 种类型:
// 1、执行静态SQL语句。通常通过Statement实例实现。
// 2、执行动态SQL语句。通常通过PreparedStatement实例实现。
// 3、执行数据库存储过程。通常通过CallableStatement实例实现。

        Statement stmt = null;        try {            stmt = con.createStatement() ;        } catch (SQLException e) {            e.printStackTrace();            System.out.println("创建Statement失败!");        }

第五步 获取结果集解析数据:

        ResultSet reSet = null;        try {            reSet= stmt.executeQuery("select   *  FROM   tab1");            while(reSet.next()){                String name =  reSet.getString("name");                System.out.println("名称 "+name+"!");            }        } catch (SQLException e) {            e.printStackTrace();        }

第六步关闭链接:

     //关闭声明        if(stmt!=null){            try {                stmt.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        //关闭结果集        if(reSet!=null){            try {                reSet.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        //关闭连接        if(con!=null){            try {                con.close();            } catch (SQLException e) {                e.printStackTrace();            }        }

出现的错误 Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false’. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

原因:是MySQL在高版本需要指明是否进行SSL连接

解决方法 :SSL 需要设置一个属性 setting useSSL=false, or set useSSL=true
String url = “jdbc:mysql://localhost:3306/test?useSSL=true” ;

友情链接:http://www.cnblogs.com/hongten/archive/2011/03/29/1998311.html

0 0
原创粉丝点击