[学习笔记] JDBC的简单使用_01

JDBC简单操作

步骤

回忆一下我们平常操作数据库(以MySql为例)的步骤是什么?

  • 打开数据库
  • 输入密码
  • 输入SQL语句
  • 回车
  • 关闭

使用JDBC操作数据库的步骤是一样的, 只是形式不一样. JDBC用Java代码来操作数据库

  • 加载注册驱动(打开数据库)
  • 获取连接对象(输入密码)
  • 创建语句对象(输入SQL语句)
  • 执行SQL语句(回车)
  • 释放资源(关闭)

加载注册驱动

好比是打开数据库

java代码是Class.forName("");

:

//如果是操作MySql
Class.forName("com.mysql.jdbc.Driver");
//如果是操作SQL server
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

哪家的数据库, 就拷贝哪家的数据库驱动包


获取连接对象

建立数据库连接, 好比操作数据库时输入密码

java代码是Connection conn = ManagerDriver.getConnection(String database_url, String username, String password);

  • 数据库url -> jdbc:mysql://ip:端口/数据名, 如:jdbc:mysql://localhost:3306/jdbcdemo
  • 数据库url, 用户名, 密码合称为连接数据库三要素

Jdbc程序中的Connection,它用于代表数据库的连接,Collection是数据库编程中最重要的一个对象,客户端与数据库所有交互都是通过connection对象完成的


创建语句对象

类似操作数据库时创建一个SQL语句(虽然不是这么回事, 但可以先这么理解)

java代码: Statement st = conn.createStatement();
语句对象用于执行SQL语句


执行SQL

  • 查询sql: st.executeQuery(sql);
  • 其他sql: st.executeUpdate(sql);

数据库建表操作(DDL)

将上述步骤合并在一起即可

package jdbcdemo-test1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import org.junit.Test;

public class DDLDemo {
	//创建t_student表
	@Test
	public void test01() throws Exception{
		String sql = "CREATE TABLE t_student(id BIGINT(20) PRIMARY KEY AUTO_INCREMENT,sname VARCHAR(20),age INT(10));";
		
		//1. 加载注册驱动
		Class.forName("com.mysql.jdbc.Driver");
		//2. 获取链接对象
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "1092568516");
		//3. 创建语句对象
		Statement st = conn.createStatement();
		//4. 执行SQL语句
		int row = st.executeUpdate(sql);
		//5. 释放资源
		st.close();
		conn.close();
		
		System.out.println(row);
	}
	
	//正确处理异常应该如下(不抛出异常)
	@Test
	public void test02(){
		String sql = "CREATE TABLE t_student(id BIGINT(20) PRIMARY KEY AUTO_INCREMENT,sname VARCHAR(20),age INT(10));";
		
		//声明需要关闭的资源
		Connection conn = null;
		Statement st = null;
		try{
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "1092568516");
			st = conn.createStatement();
			st.executeUpdate(sql);
		}catch(Exception e){
			
		}finally{
			try{
				if(st != null){				
					st.close();
				}
			}catch(Exception e){
				
			}finally{
				try{
					if(conn != null){				
						conn.close();
					}
				}catch(Exception e){
					
				}				
			}
		}
	}
}

增删改操作(DML)

与建表操作类似

将上述步骤(加载注册驱动, 获取连接对象, 创建语句对象, 执行SQL, 释放资源)连接起来即可

代码如下:

package jdbcdemo-test1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import org.junit.Test;

public class DMLTest {

	//插入操作
	@Test
	public void testInsert() throws Exception{
		String sql = "INSERT INTO t_student (sname, age) VALUES('Fighter', 21)";
        
        //1. 加载注册驱动
		Class.forName("com.mysql.jdbc.Driver");
        //2. 获取连接对象
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "1092568516");
        //3. 创建语句对象
		Statement st = conn.createStatement();
        //4. 执行插入SQL. 返回受影响行数
		int row = st.executeUpdate(sql);
        //5. 释放资源
		st.close();
		conn.close();
        
		System.out.println(row);//输出: 1
	}
	
    //修改操作
	@Test
	public void testUpdate() throws Exception{
		String sql = "UPDATE t_student SET sname = 'Narsilion' WHERE id = 1 ";
        
        //1. 加载注册驱动
		Class.forName("com.mysql.jdbc.Driver");
        //2. 获取连接对象
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "1092568516");
        //3. 创建语句对象
		Statement st = conn.createStatement();
        //4. 执行修改SQL. 返回受影响行数
		int row = st.executeUpdate(sql);
        //5. 释放资源
		st.close();
		conn.close();
        
		System.out.println(row);//输出: 1		
	}
	
    //删除操作
	@Test
	public void testDelete() throws Exception{
		String sql = "DELETE FROM t_student WHERE id = 1";
        
        //1. 加载注册驱动
		Class.forName("com.mysql.jdbc.Driver");
        //2. 获取连接对象
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "1092568516");
        //3. 创建语句对象
		Statement st = conn.createStatement();
        //4. 执行删除SQL. 返回受影响行数
		int row = st.executeUpdate(sql);
        //5. 释放资源
		st.close();
		conn.close();
        
		System.out.println(row);//输出: 1			
	}
}

查询操作(DQL)

查询操作与其他其他操作不同的是, 查询操作会返回查询结果. 我们将该结果成为结果集, 即ResultSet

package jdbcdemo-test1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.junit.Test;

public class DQLTest {

	//查询t_student一共多少条数据
	@Test
	public void test01() throws Exception{
		String sql = "SELECT COUNT(id) FROM t_student";
        
        //1. 加载注册驱动
		Class.forName("com.mysql.jdbc.Driver");
        //2. 获取连接对象
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "1092568516");
        //3. 创建语句对象
		Statement st = conn.createStatement();
        //4. 执行查询SQL. 返回结果集对象, 封装结果集
		ResultSet rs = st.executeQuery(sql);
		
        //next(): 返回当前结果集的下一行. 无则返回none
		if(rs.next()){
        	//返回第一列的值
			//Long totalCount = rs.getLong(1);
            
            //返回列名的值
			Long totalCount = rs.getLong("COUNT(id)");
			System.out.println(totalCount);
		}
		
		rs.close();
		st.close();
		conn.close();
	}
	
	//查询t_student表中id为2的数据
	@Test
	public void test02() throws Exception{
		String sql = "SELECT * FROM t_student WHERE id=2";
        
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "1092568516");
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery(sql);
		
		if(rs.next()){
			Long id = rs.getLong("id");
			String sname = rs.getString("sname");
			Long age = rs.getLong("age");
			
			System.out.println(id + ", " + sname + ", " + age);
		}
		
		rs.close();
		st.close();
		conn.close();
	}
	
	//查询s_student表中所有数据
	@Test
	public void test03() throws Exception{
		String sql = "SELECT * FROM t_student";
        
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "1092568516");
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery(sql);
		
		while(rs.next()){
			Long id = rs.getLong("id");
			String sname = rs.getString("sname");
			Long age = rs.getLong("age");
			
			System.out.println(id + ", " + sname + ", " + age);
		}
		
		rs.close();
		st.close();
		conn.close();
	}
}

Jdbc程序中的ResultSet用于代表Sql语句的执行结果Resultset封装执行结果时,采用的类似于表格的方式,ResultSet对象维护了一个指向表格数据行的游标,初始的时候,游标在第一行之前,调用ResultSet.next()方法,可以使游标指向具体的数据行,进行调用方法获取该行的数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值