传智播客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:框架就是将公用的东西抽象出来,然后将业务往上填即可
传智播客JavaWeb day10-jdbc操作mysql、连接数据库六大步骤的更多相关文章
- 传智播客JavaWeb day01 快捷键、XML
2015-01-14 一直计划着学习java,今天晚上终于下定决心看了下传智播客朴乾老师的javaweb开发视频day01之第一讲,主要内容是开发工具简单介绍.怎么创建工程.Junit的介绍,我是C# ...
- 传智播客JavaWeb day09-mysql入门、数据库操作、数据库表操作、数据行操作
不知不觉已到了第九天了,今天主要讲了关系数据库的基本概述.安装.数据库.表和数据行的操作 1. 基本概述 1.1 数据库就是用来存储数据的.早期是存在文件里面的操作起来效率低而且不是很安全. 1.2 ...
- 传智播客JavaWeb听课总结
一. JavaWeb基础 第一天: 1.Eclipse详解: (1).Bad versionnumber in .class file:编译器版本和运行(JRE)版本不符合.高的JRE版本兼容低版本的 ...
- 传智播客JavaWeb day07、day08-自定义标签(传统标签和简单标签)、mvc设计模式、用户注册登录注销
第七天的课程主要是讲了自定义标签.简单介绍了mvc设计模式.然后做了案例 1. 自定义标签 1.1 为什么要有自定义标签 前面所说的EL.JSTL等技术都是为了提高jsp的可读性.可维护性.方便性而取 ...
- 传智播客JavaWeb day11--事务的概念、事务的ACID、数据库锁机制、
1. 什么叫做事务? 2.默认情况下每一条sql语句都是一个事务,然后自动提交事务 ps:如果想多条语句占一个事务,则可以手动设置SetAutoCommit为false 3.关键字 start tr ...
- 传智播客JavaWeb day05-session、url重写
1.session是什么 1.1 session是一种会话技术 ps:还有一种是cookie 2.session的作用 2.1 服务器端会话范围内的数据共享 3.session的生命周期 3.1何时 ...
- 传智播客JavaWeb day02笔记
2015年1月21日 今天的主要内容:介绍了几款常用Javaweb服务器,重点介绍了tomcat以及tomcat的安装和怎么样检测安装成功 1.JavaWeb常见服务器 Tomcat(免费但是只支持部 ...
- 传智播客JavaWeb day03
ServletContext 这堂课主要讲ServletContext这个web域(可以看得见范围的)对象,web在启动的时候会创建唯一的ServletContext域对象. 作用:1.用来web域共 ...
- 传智播客JavaWeb day06-jstl
一.jsp标签(sun公司提供的) 二.EL表达式 三.jstl (javaserver pages standard tag library) 1.为什么要有jstl jsp标签太弱,el表达式功能 ...
随机推荐
- 第一篇博客:Hello World
2016年10月10日,双十,好日子,决定开始写第一篇博客,标题想了会,就叫Hello World 吧,哈哈^_^. 首先感谢博客园的管理们能批准我的申请,记得在14年的时候申请过一次,竟然没申请通过 ...
- 服务器asp.net 3.5 HTTP 错误 500.19 - Internal Server Error 无法访问请求的页面,因为该页的相关配置数据无效。
配置错误:不能在此路径中使用此配置节.如果在父级别上锁定了该节,便会出现这种情况.锁定是默认设置的(overrideModeDefault="Deny"),或者是通过包含 over ...
- SVN使用教程
SVN简介: 为什么要使用SVN? 程序员在编写程序的过程中,每个程序员都会生成很多不同的版本,这就需要程序员有效的管理代码,在需要的时候可以迅速,准确取出相应的版本. Subversion是什么? ...
- 1310. ACM Diagnostics
http://acm.timus.ru/problem.aspx?space=1&num=1310 题目中说的 “the lexicographically increasing list” ...
- Java如何解决脆弱基类(基类被冻结)问题
概述 大多数好的设计者象躲避瘟疫一样来避免使用实现继承(extends 关系).实际上80%的代码应该完全用interfaces写,而不是通过extends.“JAVA设计模式”一书详细阐述了怎样用 ...
- IntelliJ IDEA 14.x 与 Tomcat 集成,创建并运行Java Web项目
转自:http://www.php-note.com/article/detail/854 IntelliJ IDEA 14.x 与 Tomcat 集成,创建并运行Java Web项目 作者:php- ...
- oc--UINavigationController控制器
UINavigationController导航控制器 UINavigationController导航控制器,是多个界面间跳转的重要元素,可以理解为它存储着多个viewController,它的存储 ...
- Android Binder
http://blog.csdn.net/luoshengyang/article/details/6618363 Android进程间通信(IPC)机制Binder简要介绍和学习计划
- VisualSVN5.0.1补丁原创发布
VisualSVN5.0.1补丁原创发布
- DataList无数据如何显示
<FooterTemplate> <asp:Label runat="server" ID="emptyLb" Text="No D ...