您的位置:首页 > 编程语言 > Java开发

jdbc-mysql基础 注册驱动 Class.forName

2017-11-16 11:51 169 查看
礼悟:
   公恒学思合行悟,尊师重道存感恩。叶见寻根三返一,江河湖海同一体。
虚怀若谷良心主,愿行无悔给最苦。读书锻炼养身心,诚劝且行且珍惜。

  数据、数据,命根就在数据。大数据、AI等技术,都是以数据为基础。操作数据库一定要谨慎小心。给最苦 这里的代码,看看就好,要有自己的判断。遇到抉择,要不耻上下问。

javaSE:8
mysql:5.7.14
mysql-connector-java:5.1.44
os:windows7 x64
ide:MyEclipse 2017


特制的异常类

package com.jizuiku;

/**
* 这个类很重要,即完成了抛异常的动作、通过编译,又可以使数据逻辑层的接口保持简洁。
*
* @author 博客园-给最苦
* @version V17.11.08
*/
public class DaoException extends RuntimeException {

/**
*
*/
private static final long serialVersionUID = 1L;

public DaoException() {
// TODO Auto-generated constructor stub
}

public DaoException(String message) {
super(message);
// TODO Auto-generated constructor stub
}

public DaoException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}

public DaoException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}

public DaoException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}

}


JDBCUtils类的代码

package com.jizuiku;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
*
*
* @author 给最苦
* @version V17.11.07
*/
public final class JDBCUtils {

/**
* url格式 -> jdbc:子协议:子名称//主机名:端口号/数据库的名字?属性名=属性值&属性名=属性值
* configString变量中有多个参数,需要深入地去研究它们的具体含义
*/
private static String configString = "?useUnicode=true&characterEncoding=utf8&useSSL=true";
private static String url = "jdbc:mysql://localhost:3306/jdbcforjava" + configString;
// 本地的mysql数据库(无子名称) 端口号3306 数据库jdbcforjava

private static String user = "root";
private static String password = "";

// 工具类,直接使用,不可生对象
private JDBCUtils() {
}

// 注册驱动,这里应用的是static代码块只执行一次的特点
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
throw new ExceptionInInitializerError(e);
}
}

/**
* 获取与指定数据库的链接
*
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}

/**
* 释放三种资源ResultSet PreparedStatement Connection
*
*/
public static void free(ResultSet rs, PreparedStatement ps, Connection con) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new DaoException(e.getMessage(), e);
} finally {
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new DaoException(e.getMessage(), e);
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new DaoException(e.getMessage(), e);
}
}
}
}
}


数据库中的数据展示



测试类代码

package com.jizuiku;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* 演示类
*
* @author 博客园-给最苦
* @version V2017.11.13
*/
public class Demo {

public static void main(String[] args) {

Connection conn = null;
PreparedStatement ps= null;
ResultSet rs = null;

try {
// 得到链接
conn = JDBCUtils.getConnection();

// 要把列名写出来,目的方便后续的取数据
String sql = "select id,name,quantity,time,price from book";
ps = conn.prepareStatement(sql);

// 执行语句 因为执行的语句会返回多行多列,所以使用executeQuery语句
rs = ps.executeQuery();

// 查询并输出数据
while (rs.next()) {
System.out.println(rs.getObject("id") + " " +
rs.getObject("name") + " " +
rs.getObject("quantity") + " "+
rs.getObject("time") + " " +
rs.getObject("price"));
}

} catch (SQLException e) {
// TODO Auto-generated catch block
throw new DaoException(e.getMessage(),e);
}

// 释放资源
JDBCUtils.free(rs,ps,conn);
}

}


效果展示



看完演示之后,你是否生出了这样的疑问:为什么呢?Class.forName()就能注册驱动了,什么原理? 请看下面地分解。

  找源代码



  打开看看

/*
Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.

The MySQL Connector/J is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
this software, see the FOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; version 2
of the License.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this
program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth
Floor, Boston, MA 02110-1301  USA

*/

package com.mysql.jdbc;

import java.sql.SQLException;

/**
* The Java SQL framework allows for multiple database drivers. Each driver should supply a class that implements the Driver interface
*
* <p>
* The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to
* connect to the target URL.
*
* <p>
* It is strongly recommended that each Driver class should be small and standalone so that the Driver class can be loaded and queried without bringing in vast
* quantities of supporting code.
*
* <p>
* When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a
* driver by doing Class.forName("foo.bah.Driver")
*/
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
//
// Register ourselves with the DriverManager
//
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}

/**
* Construct a new driver and register it with DriverManager
*
* @throws SQLException
*             if a database error occurs.
*/
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
}


  通过类的名字,将类装载到虚拟机中。一装载就会调用类的static代码块,就是通过这个机制来实现注册的

学习资源:itcast和itheima视频库。如果您有公开的资源,可以分享给我的话,用您的资源学习也可以。
博文是观看视频后,融入思考写成的。博文好,是老师讲得好。博文坏,是 给最苦 没认真。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: