日期:2014-05-16 浏览次数:20521 次
JDBC简介
第一个JDBC程序步骤
Connection conn = DriverManager.getConnection(url,user,pass);
创建用于向数据库发送SQL的Statement对象,并发送sql
Statement st = conn.createStatement();
ResultSet rs = st.excuteQuery(sql);
从代表结果集的ResultSet中取出数据,打印到命令行窗口
断开与数据库的连接,并释放相关资源
package net.csdn.JDBC; import java.sql.*; public class TestJDBC1 { /** * @param args */ public static void main(String[] args) { Connection con = null; Statement st = null; ResultSet rs = null; try { //加载驱动 Class.forName("com.mysql.jdbc.Driver"); //创建连接 String url = "jdbc:mysql:///tsgl"; con = DriverManager.getConnection(url,"root","123456"); //创建语句对象 st = con.createStatement(); //执行查询语句 String sql = "select sno,sname,tie,stelephone,borrowcount from user"; rs = st.executeQuery(sql); //遍历结果集 while(rs.next()){ System.out.println(rs.getString("sno")); System.out.println(rs.getString("sname")); System.out.println(rs.getString("tie")); System.out.println(rs.getString("stelephone")); System.out.println(rs.getString("borrowcount")); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //释放资源 if(rs != null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(st != null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(con != null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
程序详解—DriverManager
Jdbc程序中的DriverManager用于加载驱