连接JDBC的工具类

连接JDBC的工具类

此类的功能:
  1. 获取连接
  2. 释放资源
    可以把每段代码中重复的部分抽取出来,单独放到一个类中,这样其他的类都可以引用。
    在这里插入图片描述
package com.test.jdbc01;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 此类是连接JDBC的工具类 功能: 1、获取连接 2、释放资源
 * 
 */
public class JDBCUtils {
	// 声明全局变量
	static String user;
	static String password;
	static String driver;
	static String url;

	static {

		try {
			Properties info = new Properties();
			info.load(new FileInputStream("src\\jdbc.properties"));
			user = info.getProperty("user");
			password = info.getProperty("password");
			driver = info.getProperty("driver");
			url = info.getProperty("url");
			// 1、注册驱动
			Class.forName(driver);
		} catch (Exception e) {
			// 将编译异常转换为运行异常
			throw new RuntimeException(e);
		}

	}

	/**
	 * 功能:获取可用的连接对象
	 */
	public static Connection getConnection() throws Exception {

		// 2、获取连接
//		Connection connection = DriverManager.getConnection(url, user, password);
		return DriverManager.getConnection(url, user, password);
	}

	// 关闭连接
	public static void close(ResultSet set, Statement statement, Connection connection) throws Exception {
		// 如果不为空,则关闭
		if (set != null) {
			set.close();
		}
		if (statement != null) {
			statement.close();
		}
		if (connection != null) {
			connection.close();
		}
	}

}

package com.test.jdbc01;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;
import java.util.Scanner;

public class TestPreparedStatement {

	public static void main(String[] args) throws Exception {

		// 界面
		Scanner input = new Scanner(System.in);

		System.out.println("请输入待修改的人员ID编号:");

		int id = input.nextInt();

		System.out.println("请输入新的人员姓名:");

		String name = input.next();

		// =============== 连接数据库的步骤====================

		// 1、获取连接
		Connection connection = JDBCUtils.getConnection();

		// 2、执行增删改查
		String sql = "update beauty set name=? where id=?";
		PreparedStatement statement = connection.prepareStatement(sql);
		statement.setString(1, name);
		statement.setInt(2, id);
		// 拿到一个update变量,返回受影响的行数
		int update = statement.executeUpdate();
		System.out.println(update > 0 ? "修改成功!" : "修改失败!");

		// 3、释放资源
		JDBCUtils.close(null, statement, connection);
	}
}

在这里插入图片描述
就酱.@_@

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值