java头歌-JDBC基础编程练习

第1关:JDBC更新员工密码

在这里插入图片描述

package step1;

import java.sql.*;

public class UpdatePass {
	// 修改数据
	public static void updateDB() {

		/********* Begin *********/

		// 第一步:加载驱动
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e1) {
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
		}

		// 第二步:建立连接, "root"和"123123"是针对MySQL设置了用户名(root)和密码(123123)的情况
		// 127.0.0.1:3306是mysql服务器地址及端口 数据库编码格式设置为utf-8
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			String url = "jdbc:mysql://127.0.0.1:3306/tsgc?useUnicode=true&characterEncoding=utf8";
			String user = "root";
			String password = "123123";
			conn = DriverManager.getConnection(url, user, password);
			// 第三步:建立statement对象

			String sql = "update employee set password='hello' where sex='女'";
			ps = conn.prepareStatement(sql);

			// 第四步:修改数据
			ps.execute();
			// 第五步:关闭statement对象和连接对象
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			try {
				ps.close();
				conn.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}

		}

		/********* End *********/
	}
}

第2关:JDBC查询员工信息

在这里插入图片描述

package step1;

import java.sql.*;

public class QueryPass {

	// 查询数据代码不用上实验报告
	public static void queryDB() {

		/********* Begin *********/
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			// 第一步:加载驱动
			Class.forName("com.mysql.jdbc.Driver");

			// 第二步:建立连接, "root"和"123123"是针对MySQL设置了用户名(root)和密码(123123)的情况
			// 127.0.0.1:3306是mysql服务器地址及端口 数据库编码格式设置为utf-8
			String url = "jdbc:mysql://127.0.0.1:3306/tsgc?useUnicode=true&characterEncoding=utf8";
			String user = "root";
			String password = "123123";
			conn = DriverManager.getConnection(url, user, password);

			// 第三步:建立statement对象
			String sql = "select * from employee";
			ps = conn.prepareStatement(sql);

			ResultSet rs = ps.executeQuery();
			// 第四步:查询数据

			while (rs.next()) {
				String no = rs.getString(1);
				String name = rs.getString(2);
				Object password1 = rs.getString(3);
				Object sex = rs.getString(4);
				double salary = rs.getDouble(5);
				System.out.println("no:" + no + "\tname:" + name + "\tpassword:" + password1 + "\tsex:" + sex
						+ "\tsalary:" + salary);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 第五步:关闭statement对象和连接对象

			try {
				ps.close();
				conn.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}

		/********* End *********/
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值