一、步骤介绍
1.通过Class.forName()加载驱动;
2.通过DriverManager.getConnection()获取Conncetion连接对象;
3.创建Statement对象传递sql语句到数据库执行;
4.接收ResultSet查询结果;
5.释放资源。
二、查询案例
public void getData(){ String URL = "jdbc:sqlserver://127.0.0.1:1433;databaseName=news"; Connection con=null; try { // 加载驱动 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // 获得数据库连接对象 con = DriverManager.getConnection(URL, "sa", "12345yehuan"); // 执行sql语句 String sql = "select * from student"; Statement statement = con.createStatement(); // 接收查询结果 ResultSet rs = statement.executeQuery(sql); while(rs.next()){ int id = rs.getInt(1); String name = rs.getString(2); int age = rs.getInt(3); System.out.println(id+"\t"+name+"\t"+age); } System.out.println("连接成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { // 释放资源 con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
原文地址:https://www.cnblogs.com/YeHuan/p/10886748.html
时间: 2024-10-12 05:50:45