传智播客JavaWeb day10-jdbc操作mysql、连接数据库六大步骤

  第十天主要讲了jdbc操作mysql数据库,包括连接数据库六大步骤(注册数据库驱动、获得连接对象connetion、生成传输器stament、执行查询获得ResultSet、遍历结果集、关闭资源)、介绍了连接数据库的常用对象(Drivermanage、Connection、Statement、ResultSet)、对大文本二进制的操作、对user案例进行了改进、sql批处理、利用泛型工厂类解耦、sql注入的介绍、最后复习了下前十天的课程


连接数据库的六大步骤

1.注册数据库驱动

  1.1 DriverManager

    1.1.1 注册驱动  DriverManager.registerDriver(new com.mysql.jdbc.Driver())

    1.1.2 问题

        1.1.2.1 当我们查看new com.mysql.jdbc.Driver()的源代码时我们会发现Driver类中有一段静态代码块将驱动又注册了一次(如下代码片段),这样一来,利用RegisterDriver方法注册数据库驱动的时候,相当于将驱动注册了两次,所以不推荐这种方式,推荐使用class.forName(clazz)的方式。

/*
Copyright (C) 2002-2004 MySQL AB This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation. There are special exceptions to the terms and conditions of the GPL
as it is applied to this software. View the full text of the
exception in file EXCEPTIONS-CONNECTOR-J in the directory of this
software distribution. 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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")
*
* @see org.gjt.mm.mysql.Connection
* @see java.sql.Driver
* @author Mark Matthews
* @version $Id: Driver.java 3726 2005-05-19 15:52:24Z mmatthews $
*/
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
// ~ Static fields/initializers
// --------------------------------------------- //
// Register ourselves with the DriverManager
//
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
} // ~ Constructors
// ----------------------------------------------------------- /**
* 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()
}
}

  1.2 Class.forName

    class.forName("com.mysql.jdbc.Driver")

    ps:C#中注册驱动的方式是在连接字符串上写上Provider Name="System.Data.SqlClient" ,odbc内部机制会自动加载注册驱动  

2.创建(获取)连接对象

  2.1 Conneciton conn = DriverManager.getConnection(url)

   2.2 url格式:jdbc:mysql:locahost/dept或者简写成jdbc:mysql:///dept

3.创建传输器

   conn.createStatement()(获取得到的statement不支持sql语句的预编译,容易导致sql注册后面会通过他的子类PreparedStatement来解决sql注入这个问题)

4.执行sql命令获得ResultSet

    ResultSet rs = statement.query(sql)

5. 遍历结果集

  rs.next()跟C#中DataReader.Read()一样都是有个像游标一样的机制

6.关闭资源

  因为操作数据库的这些对象都是非托管的对象,所有用完之后要手动关闭,否则会影响机器的性能。 ps:关闭的时候一定要放在finally代码块中关闭,然后还要判读资源对象为null的情况

如:

public static void close(Statement statement,ResultSet resultset,Connection conn) {
if (statement!=null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
statement = null;
}
}
if (resultset != null) {
try {
resultset.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
resultset = null;
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn = null;
}
}
}

ps:注意当一个对象被设置为null时,没有任何对象引用的时候就会被当做垃圾对象回收,刚好Java有垃圾回收机制,所有当资源在关闭的时候出现了异常最后也会被设置成null然后被回收


JDBCUtils的演进

  当在使用jdbc操作mysql数据库的时候,方法add、update、delete中有大部分的代码都是一样,如:获取connetion对象和关闭获取资源,所以我想将这些共有的代码抽取到一个工具类中,然后将url中的连接信息放在一个config.properties的配置文件中

1. 我不希望工具类被new于是我将构造函数私有化

2.我希望配置信息全局只加载一次,那么我将配置文件的加载放在static静态代码块中,然后数据库驱动也只注册一次

3.方法都应该是static静态的

代码如下:

package com.chenlh.util;

import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; public class JDBCUtil {
private static Properties pro = null;
private JDBCUtil(){ }
static{
//加载资源文件
pro = new Properties();
try {
pro.load(new FileReader(JDBCUtil.class.getClassLoader().getResource("config.properties").getPath()));
Class.forName(pro.getProperty("driver"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException("读取配置文件出错了!");
}
}
public static Connection getConnection() throws ClassNotFoundException, SQLException { //注册驱动
// Class.forName(pro.getProperty("driver"));
//创建连接
return DriverManager.getConnection(pro.getProperty("url"), pro.getProperty("user"),pro.getProperty("password"));
} public static void close(Statement statement,ResultSet resultset,Connection conn) {
if (statement!=null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
statement = null;
}
}
if (resultset != null) {
try {
resultset.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
resultset = null;
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn = null;
}
}
}
}

PS:代码在中如果我不想对异常进行捕捉和处理的话我可以通过throws或者直接throw一个异常抛出上一级处理

PS:框架就是将公用的东西抽象出来,然后将业务往上填即可

上一篇:PyQt5+Python3.5.2-32bit开发环境搭建


下一篇:LG1198/BZOJ1012 「JSOI2008」最大数 线段树+离线