JDBC开发步骤

  • 注册驱动:Class.forName("com.mysql.jdbc.Driver");
  • 获得连接:Connnection conn = DriverManager.getConnection("root", "123", "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF8");
  • 获得语句执行者:Statement stmt = conn.createStatement();
  • 执行sql语句
  • 处理结果
  • 释放资源

JDBC开发代码示例

private static void login(String username, String password) throws Exception {
		// 注册驱动
		Class.forName("com.mysql.jdbc.Driver");
		// 获取连接
		String url = "jdbc:mysql://localhost:3306/web15";
		Connection conn = DriverManager.getConnection(url, "root", "123");
		// 书写sql语句
		String sql = "select * from user where username = ? and password = ?";
		// 创建执行sql语句的对象
		PreparedStatement pstmt = conn.prepareStatement(sql);

		// 设置参数
		pstmt.setString(1, username);
		pstmt.setString(2, password);

		ResultSet rs = pstmt.executeQuery();

		// 处理结果集
		if (rs.next()) {
			System.out.println("恭喜你," + username + "登录成功!");
			System.out.println(sql);
		} else {
			System.out.println("用户名或密码错误");
		}

		//关闭资源
		if (rs != null) {
			rs.close();
		}
		if (pstmt != null) {
			pstmt.close();
		}
		if (conn != null) {
			conn.close();
		}
	}
posted @ 2022-12-22 15:27  小彭先森  阅读(18)  评论(0编辑  收藏  举报