数据库连接池——JDBC


版权声明


JDBC学习笔记

JDBC操作步骤:
第一步:加载驱动
Class.forName("com.mysql.jdbc.Driver");
第二步:创建连接

利用java.sql.Drivermanager类中的getConnection()方法与数据库建立连接。

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
第三步:创建PreparedStatement对象
  • 创建Statement对象,利用java.sql.Connection创建用于执行SQL语句的Statement(不推荐使用)。
Statement statement = connection.createStatement();
  • PreparedStatement是Statement的子接口,它可以预编译 SQL
    语句并将预编译后的SQL语句存储在PreparedStatement对象中。由于 PreparedStatement
    对象已预编译过,所以其执行速度要快于 Statement对象(推荐使用)。
PreparedStatement preparedStatement = connection.prepareStatement(sql);
第四步:执行SQL语句

常用方法:
execute(String sql)
该方法可以执行任意SQL语句。当且仅当执行select语句且有返回结果时该方法返回true, 其他情况下该方法返回false。
executeUpdate(String sql)
该方法常用于执行( INSERT、DELETE、UPDATE、SELECT)Sql语句。

preparedStatement.executeUpdate();

executeQuery( String sql)
该方法通常执行査询语句,执行后返回代表结果集的ResultSet对象

resultSet = preparedStatement.executeQuery();
第五步:处理结果

在从ResultSet中获取到数据库中数据后将数据封装到JavaBean中。

第六步:关闭资源

当数据库资源用完后在finally代码块中关闭与数据库操作相关的资源,进行资源的释放。


实例:

商品主要信息为:商品编号,商品名称,商品价格,商品描述等信息。
要求如下:
(1).利用MySQL数据库存储商品
(2).利用JDBC实现对商品的CRUD,其中查询分为两种:查询单个商品和查询所有商品
(3).代码规范、整洁、逻辑严谨

  1. 在数据库中创建一张表并存入数据(student)
-- 重复测试
DROP TABLE IF EXISTS student;

-- 创建表
CREATE TABLE student (
  studentid INT,
  studentname VARCHAR(30)
);

-- 插入数据
INSERT INTO student (studentid,studentname) VALUES (1001,"小明");
INSERT INTO student (studentid,studentname) VALUES (1002,"白雪");
INSERT INTO student (studentid,studentname) VALUES (1003,"小敏");
INSERT INTO student (studentid,studentname) VALUES (1004,"小芳");
INSERT INTO student (studentid,studentname) VALUES (1005,"皮皮");

-- 査询表中所有字段的数据
SELECT * FROM student;
  1. 创建javabean商品类(Goods.java)
public class Goods {

	private String gooodsID;
	private String goodsName;
	private Integer goodsPrice;
	private String goodsInfo;

	public Goods() {
		super();
	}

	public Goods(String gooodsID, String goodsName, Integer goodsPrice, String goodsInfo) {
		super();
		this.gooodsID = gooodsID;
		this.goodsName = goodsName;
		this.goodsPrice = goodsPrice;
		this.goodsInfo = goodsInfo;
	}

	public String getGooodsID() {
		return gooodsID;
	}
	public void setGooodsID(String gooodsID) {
		this.gooodsID = gooodsID;
	}
	public String getGoodsName() {
		return goodsName;
	}
	public void setGoodsName(String goodsName) {
		this.goodsName = goodsName;
	}
	public Integer getGoodsPrice() {
		return goodsPrice;
	}
	public void setGoodsPrice(Integer goodsPrice) {
		this.goodsPrice = goodsPrice;
	}
	public String getGoodsInfo() {
		return goodsInfo;
	}
	public void setGoodsInfo(String goodsInfo) {
		this.goodsInfo = goodsInfo;
	}

	@Override
	public String toString() {
		return "商品编号:" + gooodsID + "|商品名称:" + goodsName + "|商品价格:" + goodsPrice + "|商品描述" + goodsInfo;
	}
}
  1. 编写一个工具类(JDBCUtils.java)
public class JDBCUtils {

	public static Connection getConnection() throws Exception {

		Class.forName("com.mysql.jdbc.Driver");
		int port = 3306;
		String databaseName = "mydb";
		String userName = "root";
		String password = "root";
		String url = "jdbc:mysql://localhost:" + port + "/" + databaseName;
		Connection connection = DriverManager.getConnection(url, userName, password);

		return connection;

	}

	public static void release(Connection connection, Statement statement, ResultSet resultSet) {

		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
  1. 商品实现类(GoodsJDBC.java)
public class GoodsJDBC {

	public static void main(String[] args) {

		GoodsJDBC demo = new GoodsJDBC();
		demo.addGoods("g_104", "iphone x", 8999, "手机界标杆"); // 添加商品
		demo.deleteGoods("g_104");// 删除商品
		demo.updateGoods("华为mate20", 3799, "g_104");// 修改商品
		demo.findGoods1(); // 查找所有商品
		demo.findGoods2("g_102");// 查找单个商品

	}

	// 添加商品(也可参见文末备注)
	public void addGoods(String goodsID, String goodsName, int goodsPrice, String goodsInfo) {

		Connection connection = null;
		PreparedStatement preparedStatement = null;

		try {
			// 加载驱动
			// 创建连接
			connection = JDBCUtils.getConnection();
			String sql = "insert into goods(goodsid,goodsname,goodsprice,goodsinfo)values(?,?,?,?)";
			// 创建PreparedStatement对象
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, goodsID);
			preparedStatement.setString(2, goodsName);
			preparedStatement.setInt(3, goodsPrice);
			preparedStatement.setString(4, goodsInfo);
			// 执行sql
			preparedStatement.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(connection, preparedStatement, null);

		}
	}

	// 删除商品
	public void deleteGoods(String goodsID) {

		Connection connection = null;
		PreparedStatement preparedStatement = null;

		try {
			// 加载驱动
			// 创建连接
			connection = JDBCUtils.getConnection();
			String sql = "delete from goods where goodsid=?";
			// 创建PreparedStatement对象
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, goodsID);
			// 执行sql
			preparedStatement.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(connection, preparedStatement, null);

		}
	}

	// 修改商品
	public void updateGoods(String goodsName, int goodsprice, String goodsID) {

		Connection connection = null;
		PreparedStatement preparedStatement = null;

		try {
			// 加载驱动
			// 创建连接
			connection = JDBCUtils.getConnection();
			String sql = "update goods set goodsname=?,goodsprice=? where goodsid=?";
			// 创建PreparedStatement对象
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, goodsName);
			preparedStatement.setInt(2, goodsprice);
			preparedStatement.setString(3, goodsID);
			// 执行sql
			preparedStatement.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(connection, preparedStatement, null);

		}
	}

	// 查询所有商品
	public void findGoods1() {

		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		try {
			// 加载驱动
			// 创建连接
			connection = JDBCUtils.getConnection();
			String sql = "select * from goods";
			// 创建PreparedStatement对象
			preparedStatement = connection.prepareStatement(sql);
			// 执行sql
			resultSet = preparedStatement.executeQuery();
			// 执行结果
			while (resultSet.next()) {
				String id = resultSet.getString("goodsid");
				String name = resultSet.getString("goodsname");
				int price = resultSet.getInt("goodsprice");
				String info = resultSet.getString("goodsinfo");
				Goods goods = new Goods();
				goods.setGooodsID(id);
				goods.setGoodsName(name);
				goods.setGoodsPrice(price);
				goods.setGoodsInfo(info);
				System.out.println(goods);

			}

		} catch (Exception e) {
			e.printStackTrace();

			// 关闭资源
		} finally {

			JDBCUtils.release(connection, preparedStatement, resultSet);
		}
	}

	// 查询单个商品
	public void findGoods2(String goodsID) {

		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		try {
			// 加载驱动
			// 创建连接
			connection = JDBCUtils.getConnection();
			String sql = "select * from goods where goodsid=?";
			// 创建PreparedStatement对象
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, goodsID);
			// 执行sql
			resultSet = preparedStatement.executeQuery();
			// 执行结果
			while (resultSet.next()) {
				String id = resultSet.getString("goodsid");
				String name = resultSet.getString("goodsname");
				int price = resultSet.getInt("goodsprice");
				String info = resultSet.getString("goodsinfo");
				Goods goods = new Goods();
				goods.setGooodsID(id);
				goods.setGoodsName(name);
				goods.setGoodsPrice(price);
				goods.setGoodsInfo(info);
				System.out.println(goods);
			}

		} catch (Exception e) {
			e.printStackTrace();

			// 关闭资源
		} finally {

			JDBCUtils.release(connection, preparedStatement, resultSet);
		}
	}
}

备注:在编写添加商品方法(insertGoods)中,传参数和主函数调用还可以如下,

public class GoodsJDBC {

	public static void main(String[] args) {

		GoodsJDBC demo = new GoodsJDBC();
		Goods goods = new Goods("g_104", "iphone x", 8999, "手机界标杆");
		demo.insertGoods(goods); // 添加商品

	}

	// 添加商品
	public void insertGoods(Goods goods) {


		Connection connection = null;
		PreparedStatement preparedStatement = null;

		try {
			// 加载驱动
			// 创建连接
			connection = JDBCUtils.getConnection();
			String sql = "insert into goods(goodsid,goodsname,goodsprice,goodsinfo)values(?,?,?,?)";
			// 创建PreparedStatement对象
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, goods.getGooodsID());
			preparedStatement.setString(2, goods.getGoodsName());
			preparedStatement.setInt(3, goods.getGoodsPrice());
			preparedStatement.setString(4, goods.getGoodsInfo());
			// 执行sql
			preparedStatement.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(connection, preparedStatement, null);

		}
	}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值