Java 数据库基本操作

连接数据库

要访问数据库,首先要加载数据库的驱动程序(只需要在第一次访问数据库时加载一次),然后每次访问数据时创建一个Connection对象,之后执行操作数据库的SQL语句,最后在完成数据库操作后销毁前面创建的Connection对象,释放与数据库的连接。


import java.sql.*; //导入java.sql包

public class Conn { // 创建类Conn
	Connection con; // 声明Connection对象

	public Connection getConnection() { // 建立返回值为Connection的方法
		try { // 加载数据库驱动类
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("数据库驱动加载成功");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try { // 通过访问数据库的URL获取数据库连接对象
			con = DriverManager.getConnection("jdbc:mysql:"
					+ "//127.0.0.1:3306/test", "root", "123456");
			System.out.println("数据库连接成功");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con; // 按方法要求返回一个Connection对象
	}

	public static void main(String[] args) { // 主方法
		Conn c = new Conn(); // 创建本类对象
		c.getConnection(); // 调用连接数据库的方法
	}
}

向数据库发送SQL语句

getConnection()方法只是获取与数据库的连接,要执行SQL语句首先要获得Statement类对象,通过创建的连接数据库对象的createStatement()方法可获得Statement对象。

处理查询结果集

有了Statement对象以后,可调用相应的方法实现对数据库的查询和修改,并将查询的结果集存放在ResultSet类的对象中。

顺序查询

ResultSet类的next()方法的返回值是boolean类型的数据,当游标移动到最后一行之后会返回false。

import java.sql.*;

public class Gradation { // 创建类
	static Connection con; // 声明Connection对象
	static Statement sql; // 声明Statement对象
	static ResultSet res; // 声明ResultSet对象

	public Connection getConnection() { // 连接数据库方法

		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql:"
					+ "//127.0.0.1:3306/test", "root", "123456");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con; // 返回Connection对象
	}

	public static void main(String[] args) { // 主方法
		Gradation c = new Gradation(); // 创建本类对象
		con = c.getConnection(); // 与数据库建立连接
		try {
			sql = con.createStatement(); // 实例化Statement对象
			// 执行SQL语句,返回结果集
			res = sql.executeQuery("select * from tb_stu");
			while (res.next()) { // 如果当前语句不是最后一条则进入循环
				String id = res.getString("id"); // 获取列名是"id"的字段值
				// 获取列名是"name"的字段值
				String name = res.getString("name");
				// 获取列名是"sex"的字段值
				String sex = res.getString("sex");
				// 获取列名是"birthday"的字段值
				String birthday = res.getString("birthday");
				System.out.print("编号:" + id); // 将列值输出
				System.out.print(" 姓名:" + name);
				System.out.print(" 性别:" + sex);
				System.out.println(" 生日:" + birthday);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

模糊查询

SQL语句中提供了LIKE操作符用于模糊查询,可使用“%”来代替0个或多个字符,使用下划线“_”来代替一个字符。

import java.sql.*;

public class Train { // 创建类Train
	static Connection con; // 声明Connection对象
	static Statement sql; // 声明Statement对象
	static ResultSet res; // 声明ResultSet对象
	
	public Connection getConnection() { // 与数据库连接方法
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql:"
					+ "//127.0.0.1:3306/test", "root", "123456");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con; // 返回Connection对象
	}
	
	public static void main(String[] args) { // 主方法
		Train c = new Train(); // 创建本类对象
		con = c.getConnection(); // 获取与数据库的连接
		try { // try语句捕捉异常
			sql = con.createStatement(); // 实例化Statement对象
			res = sql.executeQuery("select * from tb_stu where name like '张%'");// 执行SQL语句
			while (res.next()) { // 如果当前记录不是结果集中的最后一条,进入循环体
				String id = res.getString(1); // 获取id字段值
				String name = res.getString("name"); // 获取name字段值
				String sex = res.getString("sex"); // 获取sex字段值
				String birthday = res.getString("birthday"); // 获取birthday字段值
				System.out.print("编号:" + id); // 输出信息
				System.out.print(" 姓名:" + name);
				System.out.print(" 性别:" + sex);
				System.out.println(" 生日:" + birthday);
			}
		} catch (Exception e) { // 处理异常
			e.printStackTrace(); // 输出异常信息
		}
	}
}

预处理语句

        向数据库发送一个SQL语句,数据库中的SQL解释器负责把SQL语句生成底层的内部命令,然后执行该命令,完成相关的数据操作。如果不断地向数据库提交SQL语句,肯定会增加数据库中SQL解释器的负担,影响执行的速度。

        对于JDBC,可以通过Connection对象的preparedStatement(String sql)方法对SQL语句进行预处理,生成数据库底层的内部命令,并将该命令封装在PreparedStatement对象中,通过调用该对象的相应方法执行底层数据库命令。这样应用程序能针对连接的数据库实现将SQL语句解释为数据库底层的内部命令,然后让数据库执行这个命令,这样可以减轻数据库的负担,提高访问数据库的速度。

import java.sql.*;
public class Prep { // 创建类Perp
	static Connection con; // 声明Connection对象
	static PreparedStatement sql; // 声明预处理对象
	static ResultSet res; // 声明结果集对象
	public Connection getConnection() { // 与数据库连接方法
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql:"
					+ "//127.0.0.1:3306/test", "root", "123456");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con; // 返回Connection对象
	}
	
	public static void main(String[] args) { // 主方法
		Prep c = new Prep(); // 创建本类对象
		con = c.getConnection(); // 获取与数据库的连接
		try {
			// 实例化预处理对象
			sql = con.prepareStatement("select * from tb_stu"
					+ " where id = ?");
			sql.setInt(1, 4); // 设置参数
			res = sql.executeQuery(); // 执行预处理语句
			// 如果当前记录不是结果集中最后一行,则进入循环体
			while (res.next()) {
				String id = res.getString(1); // 获取结果集中第一列的值
				String name = res.getString("name"); // 获取name列的列值
				String sex = res.getString("sex"); // 获取sex列的列值
				// 获取birthday列的列值
				String birthday = res.getString("birthday");
				System.out.print("编号:" + id); // 输出信息
				System.out.print(" 姓名:" + name);
				System.out.print(" 性别:" + sex);
				System.out.println(" 生日:" + birthday);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

添加、修改、删除记录

可以通过SQL语句对数据执行添加、修改和删除操作。可通过PreparedStatement类的指定参数动态地对数据表中原有数据进行修改操作,并通过executeUpdate()方法执行更新语句。

import java.sql.*;

public class Renewal { // 创建类
	static Connection con; // 声明Connection对象
	static PreparedStatement sql; // 声明PreparedStatement对象
	static ResultSet res; // 声明ResultSet对象

	public Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql:"
					+ "//127.0.0.1:3306/test", "root", "123456");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}

	public static void main(String[] args) {
		Renewal c = new Renewal(); // 创建本类对象
		con = c.getConnection(); // 调用连接数据库方法
		try {
			sql = con.prepareStatement("select * from tb_stu"); // 查询数据库
			res = sql.executeQuery(); // 执行SQL语句
			System.out.println("执行增加、修改、删除前数据:");
			while (res.next()) {
				String id = res.getString(1);
				String name = res.getString("name");
				String sex = res.getString("sex");
				String birthday = res.getString("birthday"); // 遍历查询结果集
				System.out.print("编号:" + id);
				System.out.print(" 姓名:" + name);
				System.out.print(" 性别:" + sex);
				System.out.println(" 生日:" + birthday);
			}
			sql = con.prepareStatement("insert into tb_stu(name,sex,birthday) values(?,?,?)");
			sql.setString(1, "张一"); // 预处理添加数据
			sql.setString(2, "女");
			sql.setString(3, "2012-12-1");
			sql.executeUpdate();
			sql = con.prepareStatement("update tb_stu set birthday "
					+ "= ? where id = ? ");
			sql.setString(1, "2012-12-02"); // 更新数据
			sql.setInt(2, 1); // 更新数据
			sql.executeUpdate();
			Statement stmt = con.createStatement();
			stmt.executeUpdate("delete from tb_stu where id = 1");
			// 查询修改数据后的tb_stu表中数据
			sql = con.prepareStatement("select * from tb_stu");
			res = sql.executeQuery(); // 执行SQL语句
			System.out.println("执行增加、修改、删除后的数据:");
			while (res.next()) {
				String id = res.getString(1);
				String name = res.getString("name");
				String sex = res.getString("sex");
				String birthday = res.getString("birthday");
				System.out.print("编号:" + id);
				System.out.print(" 姓名:" + name);
				System.out.print(" 性别:" + sex);
				System.out.println(" 生日:" + birthday);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值