首页 > 其他分享 >JDBC开发步骤

JDBC开发步骤

时间:2022-12-22 15:34:12浏览次数:28  
标签:JDBC String 步骤 mysql 开发 sql jdbc conn pstmt

  • 注册驱动: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();
		}
	}

标签:JDBC,String,步骤,mysql,开发,sql,jdbc,conn,pstmt
From: https://www.cnblogs.com/pengsuoqun123/p/16998840.html

相关文章