Mysql:jdbc初步
【声明:】本文是作者(蘑菇v5)原创,版权归作者 蘑菇v5所有,侵权必究。本文首发在简书。如若转发,请注明作者和来源地址!未经授权,严禁私自转载!
简介:
数据库驱动:
数据库厂商为了方便开发人员从程序中操作数据库而提供的一套jar
包,通过导入这个jar
包就可以调用其中的方法操作数据库,这样的jar
包就叫做数据库驱动,下载地址一般会在该数据库的官网,比如我们这里所说的MySql
,那么mysql
的驱动就在mysql
的官网可以下载
JDBC:
sun
定义的一套标准,本质上是一大堆的操作数据库的接口,所有数据库厂商为java
设计的数据库驱动都实现过这套接口,这样一来统一了不同数据库驱动的方法,开发人员只需要学习JDBC
就会使用任意数据库驱动了
项目应用:
1、下载Mysql的connector:
将connector
的jar
包加入到classpath
中
2、注册数据库驱动,加载驱动程序
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
3、获取数据库连接connection
:
String username = "itat";
String password = "itat123";
String url = "jdbc:mysql://localhost:3306/itat_shop?
serverTimezone=UTC
&characterEncoding=utf-8&useSSL=false
&allowPublicKeyRetrieval=true";
con = DriverManager.getConnection(url, username, password);
4、获取传输器对象,利用传输器对象执行sql
语句,获取结果集对象
String sql = "select count(*) from t_user where username=?";
ps = con.prepareStatement(sql);
ps.setString(1, user.getUsername());
rs = ps.executeQuery();
5、遍历结果集获取查询结果
while (rs.next()) {
if (rs.getInt(1) > 0) {
throw new ShopException("添加的用户已经存在!不能继续添加");
}
}
6、关闭资源,释放连接
先释放resultSet
,再释放prepareStatement
,最后释放connection
finally {
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(con);
}
特别关注以下问题:
-
sql注入:使用
PreparedStatement
解决PreparedStatement
是Statement
的孩子,不同的是,PreparedStatement
使用预编译机制,在创建PreparedStatement
对象时就需要将sql
语句传入,传入的过程中参数要用?
替代,这个过程回导致传入的sql
被进行预编译,然后再调用PreparedStatement
的setXXX
将参数设置上去,由于sql
语句已经经过了预编译,再传入特殊值也不会起作用了。PreparedStatement
使用了预编译机制,sql
语句在执行的过程中效率比Statement
要高 -
整个程序域
mysql
数据库驱动绑定增加了耦合性,程序和具体的mysql
驱动绑死在一起,在切换数据库时需要改动java
代码,不够灵活:关联字符串,可以将字符串放在配置文件中,在切换数据库时就不需要改动
java
代码了 -
项目中,别人需要扩展功能:
使用接口方式,解耦合,定义接口类
-
项目中,需要替换之前的数据库(
xml
、jdbc
):使用工厂模式,提高可扩展性,反射方式,读取外部的配置文件,不用修改源码
/**
* 工厂模式
*/
public class DaoFactory {
public static IUserDao getUserDao() {
return new UserDao();//此处可以读取配置文件
}
}
-
项目中,可以使用持久化框架,简化开发流程:
Mybatis
、Hibernate
源码:
DBUtil
:
public class DBUtil {
public static Connection getConnection() {
Connection con = null;
String username = "itat";
String password = "itat123";
String url = "jdbc:mysql://localhost:3306/itat_shop?serverTimezone=UTC
&characterEncoding=utf-8
&useSSL=false
&allowPublicKeyRetrieval=true";
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
public static void close(PreparedStatement ps) {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
init.sql
:
drop database IF EXISTS itat_shop;
create database itat_shop;
use itat_shop;
create table t_user(
id int(10) primary key auto_increment,
username varchar(100),
password varchar(100),
nickname varchar(100),
status int(3),
type int(3)
);
GRANT ALL ON itat_shop.* to 'itat'@'localhost';
IUserDao
:
public interface IUserDao {
public void add (User user);
public void deleta(int id);
public void update(User user);
public User load(int id);
public List<User>list();
public User login(String username,String password);
}
UserDao
:
public class UserDao implements IUserDao {
@Override
public void add(User user) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DBUtil.getConnection();
String sql = "select count(*) from t_user where username=?";
ps = con.prepareStatement(sql);
ps.setString(1, user.getUsername());
rs = ps.executeQuery();
while (rs.next()) {
if (rs.getInt(1) > 0) {
throw new ShopException("添加的用户已经存在!不能继续添加");
}
}
sql = "insert into t_user (username,password,nickname)
value (?,?,?)";
ps = con.prepareStatement(sql);
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.setString(3, user.getNickname());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(con);
}
}
@Override
public void deleta(int id) {
Connection con = null;
PreparedStatement ps = null;
try {
con = DBUtil.getConnection();
String sql = "delete from t_user where id=?";
ps = con.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(ps);
DBUtil.close(con);
}
}
@Override
public void update(User user) {
Connection con = null;
PreparedStatement ps = null;
try {
con = DBUtil.getConnection();
String sql = "update t_user set password=?,nickname=? where id=?";
ps = con.prepareStatement(sql);
ps.setString(1, user.getPassword());
ps.setString(2, user.getNickname());
ps.setInt(3, user.getId());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(ps);
DBUtil.close(con);
}
}
@Override
public User load(int id) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
User u = null;
try {
con = DBUtil.getConnection();
String sql = "select * from t_user where id=?";
ps = con.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
while (rs.next()) {
u = new User();
u.setId(rs.getInt("id"));
u.setNickname(rs.getString("nickname"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(con);
}
return u;
}
@Override
public List<User> list() {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<User> users = new ArrayList<User>();
User u = null;
try {
con = DBUtil.getConnection();
String sql = "select * from t_user";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
u = new User();
u.setId(rs.getInt("id"));
u.setNickname(rs.getString("nickname"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
users.add(u);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(con);
}
return users;
}
@Override
public User login(String username, String password) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
User u = null;
try {
con = DBUtil.getConnection();
String sql = "select * from t_user where username=?";
ps = con.prepareStatement(sql);
ps.setString(1, username);
rs = ps.executeQuery();
while (rs.next()) {
u = new User();
u.setId(rs.getInt("id"));
u.setNickname(rs.getString("nickname"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
}
if (u == null) throw new ShopException("用户名不存在!");
if (!u.getPassword().equals(password))
throw new ShopException("用户密码不正确!");
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(con);
}
return u;
}
}
add.jsp
:
<%@ page import="itat.zttc.shop.model.User" %>
<%@ page import="itat.zttc.shop.dao.DaoFactory" %>
<%@ page import="itat.zttc.shop.dao.IUserDao" %>
<%@ page import="itat.zttc.shop.util.ValidateUtil" %><%--
Created by IntelliJ IDEA.
User: zsn10
Date: 2018/10/19
Time: 15:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String nickname = request.getParameter("nickname");
boolean validate = ValidateUtil.validateNull(
request, new String[]{"username", "password", "nickname"});
if (!validate) {
%>
<jsp:forward page="addInput.jsp"/>
<%
}
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setNickname(nickname);
IUserDao userDao = DaoFactory.getUserDao();
try {
userDao.add(user);
response.sendRedirect("list.jsp");
return;
} catch (Exception e) {
%>
<h2 style="color:red">发生错误:<%=e.getMessage()%>
</h2>
<%
}
%>