数据库操作实例

2021/5/18 19:28:11

本文主要是介绍数据库操作实例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.创建类SearchEmp,实现查找数据表tb_emp中销售部的所有成员的功能。

import java.sql.*;

public class SearchEmp {

	static Connection con;
	static Statement 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;
	}

	public static void main(String[] args) {
		SearchEmp c = new SearchEmp();
		con = c.getConnection();
		try {
			sql = con.createStatement();
			res = sql.executeQuery("select * from tb_emp where"
					+ " dapt = '销售部'");
			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();
		}
	}
}

2.编写程序,实现向数据表tb_stu中添加数据的功能,要求姓名为“李某”,性别是“女”,出生日期是“1999-10-20”。

import java.sql.*;

public class InsertStu {
	
	static Connection con;
	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;
	}
	
	public static void main(String[] args) {
		InsertStu c = new InsertStu();
		con = c.getConnection();
		try {
			sql = con.prepareStatement("insert into tb_stu(name,sex,birthday) values(?,?,?)");
			sql.setString(1, "李某");
			sql.setString(2, "女");
			sql.setString(3, "1999-10-20");
			sql.executeUpdate();
			System.out.println("数据插入成功。");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

3.编写程序,实现删除出生日期在“2010-01-01”之前的学生的功能。

import java.sql.*;

public class DeleteStu {
	static Connection con;
	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;
	}
	public static void main(String[] args) {
		DeleteStu c = new DeleteStu();
		con = c.getConnection();
		try {
			sql = con.prepareStatement("delete from tb_stu where birthday < ?");
			sql.setString(1, "2010-01-01");
			sql.executeUpdate();
			System.out.println("数据删除完毕");
		} catch (SQLException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		
	}
}



这篇关于数据库操作实例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程