JDBC_连接数据库步骤

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/Chill_Lyn/article/details/102729448
  1. 通过反射将DriverManager加载入虚拟机
  2. 利用DriverManager的静态方法getConnection()构建Connection对象与数据库获得连接
  3. 利用Connection对象构造Statement对象,编写SQL指令给Statement对象
  4. 执行Statement对象的方法将SQL指令传给数据库,若执行的SQL指令为select,则返回结果集ResultSet,若指令为其他操作,则返回受影响的行数的int值。
  5. 遍历ResultSet,使用rs.next()方法判断是否还有元素,如果有,用rs.getXXX()方法得到相应类型的值。
  6. 关闭所有连接资源

实现代码

public static void main(String[] args) throws ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver");
		Connection con= null;
		Statement s=null;
		ResultSet rs=null;
		try {
			con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "1234");
			System.out.println("连接成功");
			String sql="select * from student";
			s=con.createStatement();
			rs=s.executeQuery(sql);
			while(rs.next()) {
				String name=rs.getString("name");
				int id=rs.getInt("id");
				int age=rs.getInt("age");
				String sex=rs.getString("sex");
				String department =rs.getString("department");
				int classroom =rs.getInt("class");
				Student stu=new Student(id, name, age, sex, department, classroom);
				System.out.println(stu);
			}
		} catch (SQLException e) {
			System.out.println("连接失败");
			e.printStackTrace();
		}finally {
			try {
				if(rs!=null) {
					rs.close();
				}
				if(s!=null) {
					s.close();
				}
				if(con!=null) {
					con.close();
				}
				System.out.println("资源已经断开");
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}

猜你喜欢

转载自blog.csdn.net/Chill_Lyn/article/details/102729448