JavaWeb–JDBC(连接数据库)
JDBC的介绍
JDBC定义
JDBC一般指Java数据库连接。Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC也是Sun Microsystems的商标。我们通常说的JDBC是面向关系型数据库的。
JDBC架构
分为双层架构和三层架构。
JDBC常用API
在开发JDBC程序前,首先了解一下JDBC常用的API。JDBC API主要位于java.sql包中,该包定义了一系列访问数据库的接口和类,具体如下。
JDBC驱动程序
JDBC驱动程序共分四种类型
JDBC编程步骤
加载驱动程序:
Class.forName(driverClass)
//加载MySql驱动
Class.forName("com.mysql.jdbc.Driver")
//加载Oracle驱动
Class.forName("oracle.jdbc.driver.OracleDriver")
获得数据库连接:
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/imooc", "root", "root");
创建Statement\PreparedStatement对象:`
conn.createStatement();
conn.prepareStatement(sql);
完整实例
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DbUtil {
public static final String URL = "jdbc:mysql://localhost:3306/imooc";
public static final String USER = "liulx";
public static final String PASSWORD = "123456";
public static void main(String[] args) throws Exception {
//1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//2. 获得数据库连接
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
//3.操作数据库,实现增删改查
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT user_name, age FROM imooc_goddess");
//如果有数据,rs.next()返回true
while(rs.next()){
System.out.println(rs.getString("user_name")+" 年龄:"+rs.getInt("age"));
}
}
}
增删改查(CURD)
public class DbUtil {
public static final String URL = "jdbc:mysql://localhost:3306/imooc";
public static final String USER = "liulx";
public static final String PASSWORD = "123456";
private static Connection conn = null;
static{
try {
//1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//2. 获得数据库连接
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
return conn;
}
}
//模型
package liulx.model;
import java.util.Date;
public class Goddess {
private Integer id;
private String user_name;
private Integer sex;
private Integer age;
private Date birthday; //注意用的是java.util.Date
private String email;
private String mobile;
private String create_user;
private String update_user;
private Date create_date;
private Date update_date;
private Integer isDel;
//getter setter方法。。。
}
//---------dao层--------------
package liulx.dao;
import liulx.db.DbUtil;
import liulx.model.Goddess;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class GoddessDao {
//增加
public void addGoddess(Goddess g) throws SQLException {
//获取连接
Connection conn = DbUtil.getConnection();
//sql
String sql = "INSERT INTO imooc_goddess(user_name, sex, age, birthday, email, mobile,"+
"create_user, create_date, update_user, update_date, isdel)"
+"values("+"?,?,?,?,?,?,?,CURRENT_DATE(),?,CURRENT_DATE(),?)";
//预编译
PreparedStatement ptmt = conn.prepareStatement(sql); //预编译SQL,减少sql执行
//传参
ptmt.setString(1, g.getUser_name());
ptmt.setInt(2, g.getSex());
ptmt.setInt(3, g.getAge());
ptmt.setDate(4, new Date(g.getBirthday().getTime()));
ptmt.setString(5, g.getEmail());
ptmt.setString(6, g.getMobile());
ptmt.setString(7, g.getCreate_user());
ptmt.setString(8, g.getUpdate_user());
ptmt.setInt(9, g.getIsDel());
//执行
ptmt.execute();
}
public void updateGoddess(){
//获取连接
Connection conn = DbUtil.getConnection();
//sql, 每行加空格
String sql = "UPDATE imooc_goddess" +
" set user_name=?, sex=?, age=?, birthday=?, email=?, mobile=?,"+
" update_user=?, update_date=CURRENT_DATE(), isdel=? "+
" where id=?";
//预编译
PreparedStatement ptmt = conn.prepareStatement(sql); //预编译SQL,减少sql执行
//传参
ptmt.setString(1, g.getUser_name());
ptmt.setInt(2, g.getSex());
ptmt.setInt(3, g.getAge());
ptmt.setDate(4, new Date(g.getBirthday().getTime()));
ptmt.setString(5, g.getEmail());
ptmt.setString(6, g.getMobile());
ptmt.setString(7, g.getUpdate_user());
ptmt.setInt(8, g.getIsDel());
ptmt.setInt(9, g.getId());
//执行
ptmt.execute();
}
public void delGoddess(){
//获取连接
Connection conn = DbUtil.getConnection();
//sql, 每行加空格
String sql = "delete from imooc_goddess where id=?";
//预编译SQL,减少sql执行
PreparedStatement ptmt = conn.prepareStatement(sql);
//传参
ptmt.setInt(1, id);
//执行
ptmt.execute();
}
public List<Goddess> query() throws SQLException {
Connection conn = DbUtil.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT user_name, age FROM imooc_goddess");
List<Goddess> gs = new ArrayList<Goddess>();
Goddess g = null;
while(rs.next()){
g = new Goddess();
g.setUser_name(rs.getString("user_name"));
g.setAge(rs.getInt("age"));
gs.add(g);
}
return gs;
}
public Goddess get(){
Goddess g = null;
//获取连接
Connection conn = DbUtil.getConnection();
//sql, 每行加空格
String sql = "select * from imooc_goddess where id=?";
//预编译SQL,减少sql执行
PreparedStatement ptmt = conn.prepareStatement(sql);
//传参
ptmt.setInt(1, id);
//执行
ResultSet rs = ptmt.executeQuery();
while(rs.next()){
g = new Goddess();
g.setId(rs.getInt("id"));
g.setUser_name(rs.getString("user_name"));
g.setAge(rs.getInt("age"));
g.setSex(rs.getInt("sex"));
g.setBirthday(rs.getDate("birthday"));
g.setEmail(rs.getString("email"));
g.setMobile(rs.getString("mobile"));
g.setCreate_date(rs.getDate("create_date"));
g.setCreate_user(rs.getString("create_user"));
g.setUpdate_date(rs.getDate("update_date"));
g.setUpdate_user(rs.getString("update_user"));
g.setIsDel(rs.getInt("isdel"));
}
return g;
}
}
实战操作
实现本地查询
package cn.itcast.jdbc.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Date;
public class Example01 {
public static void main(String[] args) throws SQLException {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
// 1. 注册数据库的驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.通过DriverManager获取数据库连接
String url = "jdbc:mysql://localhost:3306/jdbc";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection (url, username,
password);
// 3.通过Connection对象获取Statement对象
stmt = conn.createStatement();
// 4.使用Statement执行SQL语句。
String sql = "select * from users";
rs = stmt.executeQuery(sql);
// 5. 操作ResultSet结果集
System.out.println("id | name | password | email | birthday");
while (rs.next()) {
int id = rs.getInt("id"); // 通过列名获取指定字段的值
String name = rs.getString("name");
String psw = rs.getString("password");
String email = rs.getString("email");
Date birthday = rs.getDate("birthday");
System.out.println(id + " | " + name + " | " + psw + " | " + email
+ " | " + birthday);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally{
// 6.回收数据库资源
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
}
package cn.itcast.jdbc.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement ;
import java.sql.SQLException;
public class Example02 {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement preStmt = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc";
String username = "root";
String password = "itcast";
// 创建应用程序与数据库连接的Connection对象
conn = DriverManager.getConnection(url, username, password);
// 执行的SQL语句
String sql = "INSERT INTO users(name,password,email,birthday)"
+ "VALUES(?,?,?,?)";
// 创建执行SQL语句的PreparedStatement 对象
preStmt = conn.prepareStatement(sql);
preStmt.setString(1, "zl");
preStmt.setString(2, "123456");
preStmt.setString(3, "zl@sina.com");
preStmt.setString(4, "1789-12-23");
preStmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally { // 释放资源
if (preStmt != null) {
try {
preStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
preStmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
}