一、JDBC
在Web开发中,不可以避免地使用数据库来储存和管理数据库。为了在java语言中提供对数据库访问的支持,SUN公司于1996年提供一套访问数据库的标准java类库,即JDBC。
1.1什么是JDBC
JDBC的全称是java数据库连接(java Database Connectivity)它是一套用于 执行SQL语句的 java APL。应用程序可通过这套APl连接到关系型数据库,并使用SQL语句来完成对数据库中数据的查询、更新、新增和删除的操作。
二、JDBCI常用的AP
示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。
三、实现第一次JDBC程序
1.搭建数据库环境
2.创建项目环境,导入数据库驱动
在Eclipse中新建一一个名称为chapter09的Web项目,将下载好的MySQL的数据库驱动文件mysql-connector-java-5.0.8- bnjan复制到项目的ib目录中,并发布到类路径下(MsSQL驱动文件可以在其官网地址: ht:/:/v.mysal.om/downloadsco.e.cor/页面中下载在浏览器中输入该地址后即可进入下载页面,单击页面Generally Available (GA) Releases窗口中的Looking for previous GA versions超链接后,在显示出的下拉框中下载所需的驱动版本即可
3.编写JDBC程序
在项目chapter09的srC目录下,新建一一个名称为cn.itcast.jdbc.example的包,在该包中创建类Example01,该类用于读取数据库中的users表,并将结果输出到控制台,如文件9-1所示。 Example01.java
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 {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection (url, username,
password);
stmt = conn.createStatement();
String sql = "select * from users";
rs = stmt.executeQuery(sql);
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{
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;
}
}
}
}
图中首先注册了MySQL的数据库驱动,通过DriverManager获取一个Connection对象,然后使用Connection对象创建一个Statement的对象,Statement对象通过excuteQuery()方法执行SQL语句,并返回结果集ResultSet。
4.PreparedStatement接口
JDBC程序中,SQL语句的执行是通过Staterment对象实现的。Statement对象每次执行SQL语句时,都会对其进行编译。当相同的SQL语句执行多次时,Statement 对象就会使数据库频繁编译相同的SQL语句,从而降低数据库的访问效率。 在chapter09项目的cn.itcast.jdbc .example包中创建一个名称为Example02的类,右类中使用PreparedStatement对象对数据库进行插入数据的操作
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 = "123456";
conn = DriverManager.getConnection(url, username, password);
String sql = "INSERT INTO users(name,password,email,birthday)"
+ "VALUES(?,?,?,?)";
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;
}
}
}
}
5.ResultSet接口
ResultSet主要用于存储结果集,可以通过nex:()方法由前向后逐个获取结果集中的数据。如果想获取结果集中任意位置的数据,则需要在创建Statement对象时,设置两个ResutSet定义的常量,具体设置方式如下。 在chapter09项目的cnitcast. jdbe example包中创建一个名称为Example03 的类,该类中使用ResultSet对象取出指定数据的信息
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;
public class Example03 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url, username, password);
String sql = "select * from users";
Statement st =conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery(sql);
System.out.print("第2条数据的name值为:");
rs.absolute(2);
System.out.println(rs.getString("name"));
System.out.print("第1条数据的name值为:");
rs.beforeFirst();
rs.next();
System.out.println(rs.getString("name"));
System.out.print("第4条数据的name值为:");
rs.afterLast();
rs.previous();
System.out.println(rs.getString("name"));
} catch (Exception e) {
e.printStackTrace();
} finally {
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;
}
}
}
}
四、使用JDBC完成数据的增删改查
1.创建JavaBean
在chapter09项目的cnitcast. jdbe example。domain包中创建一个名称为User的类,该类是一个保存用户数据的User类
package cn.itcast.jdbc.example.domain;
import java.util.Date;
public class User {
private int id;
private String username;
private String password;
private String email;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
2.创建工具类
在chapter09项目的cnitcast. jdbe example.utils包中创建一个名称为JDBCUyils的类,
package cn.itcast.jdbc.example.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
public static Connection getConnection() throws SQLException,
ClassNotFoundException {
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);
return conn;
}
public static void release(Statement stmt, Connection conn) {
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;
}
}
public static void release(ResultSet rs, Statement stmt,
Connection conn){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
release(stmt, conn);
}
}
3.创建DAO类
在src下新建一一个名称为cn.itcast.jdbc.example.dao的包,在包中创建一个名称为UsersDao的类,该类中封装了对表users 的添加、查询、删除和更新等操作
package cn.itcast.jdbc.example.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import cn.itcast.jdbc.example.domain.User;
import cn.itcast.jdbc.example.utils.JDBCUtils;
public class UsersDao {
public boolean insert(User user) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
stmt = conn.createStatement();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthday = sdf.format(user.getBirthday());
String sql = "INSERT INTO users(id,name,password,email,birthday) "+
"VALUES("
+ user.getId()
+ ",'"
+ user.getUsername()
+ "','"
+ user.getPassword()
+ "','"
+ user.getEmail()
+ "','"
+ birthday + "')";
int num = stmt.executeUpdate(sql);
if (num > 0) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, stmt, conn);
}
return false;
}
public ArrayList<User> findAll() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<User> list = new ArrayList<User>();
try {
conn = JDBCUtils.getConnection();
stmt = conn.createStatement();
String sql = "SELECT * FROM users";
rs = stmt.executeQuery(sql);
while (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setBirthday(rs.getDate("birthday"));
list.add(user);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, stmt, conn);
}
return null;
}
public User find(int id) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
stmt = conn.createStatement();
String sql = "SELECT * FROM users WHERE id=" + id;
rs = stmt.executeQuery(sql);
while (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setBirthday(rs.getDate("birthday"));
return user;
}
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, stmt, conn);
}
return null;
}
public boolean delete(int id) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
stmt = conn.createStatement();
String sql = "DELETE FROM users WHERE id=" + id;
int num = stmt.executeUpdate(sql);
if (num > 0) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, stmt, conn);
}
return false;
}
public boolean update(User user) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
stmt = conn.createStatement();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthday = sdf.format(user.getBirthday());
String sql = "UPDATE users set name='" + user.getUsername()
+ "',password='" + user.getPassword() + "',email='"
+ user.getEmail() + "',birthday='" + birthday
+ "' WHERE id=" + user.getId();
int num = stmt.executeUpdate(sql);
if (num > 0) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, stmt, conn);
}
return false;
}
}
4.创建测试类
(1)在cnitcast idbc example包中编写测试类Jdchnenrett实现向users 表中添加数据的操作
package cn.itcast.jdbc.example;
import java.util.Date;
import cn.itcast.jdbc.example.dao.UsersDao;
import cn.itcast.jdbc.example.domain.User;
public class JdbcInsertTest{
public static void main(String[] args) {
UsersDao ud = new UsersDao();
User user=new User();
user.setId(5);
user.setUsername("hl");
user.setPassword("123");
user.setEmail("hl@sina.com");
user.setBirthday(new Date());
boolean b=ud.insert(user);
System.out.println(b);
}
}
( 2 )在cn.itcast,jdbc. example包中编写测试FindAllUsersTest,该类用于实现读取users
package cn.itcast.jdbc.example;
import java.util.ArrayList;
import cn.itcast.jdbc.example.dao.UsersDao;
import cn.itcast.jdbc.example.domain.User;
public class FindAllUsersTest{
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
ArrayList<User> list = usersDao.findAll();
for (int i = 0; i < list.size(); i++) {
System.out.println("第" + (i + 1) + "条数据的username值为:"
+ list.get(i).getUsername());
}
}
}
(3) 在cn.itcast.jdbc.example包中编写测试类Findl JserByldTest,在该类中实现读取users表中指定的数据
package cn.itcast.jdbc.example;
import cn.itcast.jdbc.example.dao.UsersDao;
import cn.itcast.jdbc.example.domain.User;
public class FindUserByIdTest {
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
User user = usersDao.find(1);
System.out.println("id为1的User对象的name值为:" + user.getUsername());
}
}
(4)在cn.itcast.jdbc.example包中编写测试类UpdateUserTest,在该类中实现修改sers表中数据的操作
package cn.itcast.jdbc.example;
import java.util.Date;
import cn.itcast.jdbc.example.dao.UsersDao;
import cn.itcast.jdbc.example.domain.User;
public class UpdateUserTest{
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
User user = new User();
user.setId(4);
user.setUsername("zhaoxiaoliu");
user.setPassword("456");
user.setEmail("zhaoxiaoliu@sina.com");
user.setBirthday(new Date());
boolean b = usersDao.update(user);
System.out.println(b);
}
}
(5)在cn.itcast.jdbc example包中编写测试类DeleteUserTest, 该类实现了删除users表中数据的操作
package cn.itcast.jdbc.example;
import cn.itcast.jdbc.example.dao.UsersDao;
public class DeleteUserTest{
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
boolean b = usersDao.delete(5);
System.out.println(b);
}
}
本章总结
本章主要讲解了JDBC的基本知识,包括什么是JDBC、JDBC的常用API、如何使用JDBC,以及使用JDBC实现JDBC对数据的增删改查等知识。通过本章学习,我们可以了解到什么是JDBC,熟悉JDBC 的常用API,并且能够掌握JDBC操作数据库的步骤
2020080605013
|