Jaba_Web--JDBC 查询记录操作模板

2020-10-28 10:26:59 浏览数 (1)

代码语言:javascript复制
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Select {

	public static void main(String[] args) throws Exception {

		String driverName = "com.mysql.cj.jdbc.Driver"; // 驱动程序名
		String userName = "root"; // 数据库用户名
		String userPwd = ""; // 密码
		String dbName = "students"; // 数据库名
		String url = "jdbc:mysql://localhost:3306/"   dbName   "?useSSL=false&serverTimezone=UTC"; // 形成带数据库读写编码的数据库连接字

		Class.forName(driverName); // 加载并注册驱动程序
		Connection conn = DriverManager.getConnection(url, userName, userPwd);// 创建连接对象
		if (!conn.isClosed())
			System.out.println("Succeeded connecting to the Database!");
		Statement stmt = conn.createStatement();// 在桥conn上直接创建一辆汽车

		String sql = "select * from stu where cj>=0 and cj<=100";
		PreparedStatement pstmt = conn.prepareStatement(sql);

		ResultSet rs = pstmt.executeQuery();// 执行,得到查询结果集合
		System.out.println("记录号	 学号		姓名		成绩");
		while (rs.next()) {
			int a = rs.getRow();
			int b = rs.getInt("xh");
			String c = rs.getString("name");
			int d = rs.getInt("cj");
			System.out.println(a   " | "   b   " | "   c   " | "   d);
		}

		pstmt.close();
		stmt.close();
		conn.close();

	}

}
web

0 人点赞