JDBC

JDBC学习(一)

一、Connection连接数据池

/**
 *Connection代表应用程序和数据库的一个连接 
	 **/
	通过properties类加载jdbc.properties配置文件
	@Test

public void testGetConnection() throws Exception{
	//0.读取jdbc.properties
	/**
	 * 1).属性文件对应Java中的Properties类
	 * 2).使用类加载器加载bin目录(类路径下)的文件
	 */
	Properties properties = new Properties();
	InputStream in = ReviewTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
	properties.load(in);
	
	//1.准备获取连接的4个字符串
	String user = properties.getProperty("user");
	String password = properties.getProperty("password");
	String jdbcUrl = properties.getProperty("jdbcUrl");
	String driverClass = properties.getProperty("driverClass");
	
	//2.加载驱动:Class.forName(driverClass);
	Class.forName(driverClass);
	//3.调用
	//DriverManager.getConnection(jdbcUrl,user,password)
	//获取数据库连接
	Connection conn = DriverManager.getConnection(jdbcUrl, user, password);
	
}

二、 statement操作

通过statement对数据库进行操作

	public void teststatement() {
	Connection connection = null;
	Statement statement = null;
	
	try {
		//1.获取数据库连接
		connection = getConnection();
		//2.调用connection对象的createStatement对象
		statement =connection.createStatement();
		//3.准备SQL语句
		String sql = "UPDATA ";
		//4.发送SQL语句:调用Statement对象的executeUpdate(sql)方法
		statement.executeQuery(sql);
		//5.关闭数据库资源:由里向外关闭
		statement.close();
		connection.close();
	} catch (Exception e) {
		// TODO: handle exception
	}finally {
		releaseDB(null, statement, connection);
	}

}

编写异常方法

public void releaseDB(ResultSet re,Statement statement,Connection  connection) {

	if(re != null) {
	
		try {
			re.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	if(statement != null) {
		try {
			statement.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	if(connection != null) {
		try {
			connection.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}

查询操作

//查询操作
	public void testResultSet() {

	Connection connection = null;
	Statement statement = null;
	ResultSet re =null;
	//1.获取数据库连接
	connection = getConnection();
	//2.调用connection对象的createStatement对象
	statement =connection.createStatement();
	//3.准备SQL语句
	String sql = "SELECT  ";
	//4.发送SQL语句:调用Statement对象的executeUpdate(sql)方法
	//得到结果集对象ResultSet
	re = statement.executeQuery(sql);
	//5.处理结果集:
	//5.1调用ResultSet的next()方法:查看结果集的下一条记录是否有效
	//若有效则下移指针
	while(re.next()) {
		//5.2getXxx()方法获取具体的列的值
		int id = re.getInt(1);
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值