JDBC的CRUD操作之查询数据操作

JDBC的CRUD操作之查询数据操作

1.1.1 查询操作的代码实现

已知表数据:
在这里插入图片描述

package com.xdr630.jdbc.demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

/**
 * JDBC的CRUD的操作
 * @author xdr
 *
 */
public class JDBCDemo2 {

@Test
	/**
	 * 查询多条记录
	 */
	public void demo4(){
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try{
			// 注册驱动
			Class.forName("com.mysql.jdbc.Driver");
			// 获得连接
			conn = DriverManager.getConnection("jdbc:mysql:///web_test3", "root", "1234");
			// 执行操作
			// 创建执行SQL语句的对象:
			stmt = conn.createStatement();
			// 编写SQL:
			String sql = "select * from user";
			// 执行SQL:
			rs = stmt.executeQuery(sql);
			// 遍历结果集:
			while(rs.next()){
				System.out.println(rs.getInt("id")+" "+rs.getString("username")+" "+rs.getString("password"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			// 资源释放:
			if(rs != null){
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				
				rs = null;
			}
			if(stmt != null){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				
				stmt = null;
			}
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				conn = null;
			}
		}
	}
  • 控制台查询出表中所有数据:
    在这里插入图片描述

  • 只查询一条记录时,只要把上面编写的SQL语句作出修改即可,如:只查询一条数据

String sql = "select * from user where id = 4";
  • 控制台输出:
    在这里插入图片描述

本文来自博客园,作者:兮动人,转载请注明原文链接:https://www.cnblogs.com/xdr630/p/15254876.html

原文地址:https://www.cnblogs.com/xdr630/p/15254876.html