JDBC的典型用法

来源:互联网 发布:免费的代理服务器软件 编辑:程序博客网 时间:2024/06/12 10:02

JDBC驱动程序是Java程序和数据库之间的转换层,数据库驱动程序负责将JDBC调用成特定的数据库。

JDBC操作数据库的步骤:

代码示例

   publicstatic void main(String[]args) {

      Connection conn =null;

      PreparedStatement ps =null;

      try {

         // 1.加载数据库驱动

         Class.forName("com.mysql.jdbc.Driver");

 

         // 2.获取数据库连接

         // 其中url叫套接字,不同的数据库不同的定义规范

         // MySQL: jdbc:mysql://hostname:port/databasename

         // Oracle: jdbc:oracle:thin:@hostname:port:databasename

         // 作为本机:localhost 127.0.0.1

 

         conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tech2","root", "");

 

         // 3.创建查询对象

         ps = conn.prepareStatement("select id,name,code,age,sex from t_student");

 

         // 4.获取查询的结果集

         ResultSet rs =ps.executeQuery();

 

         // 5.遍历结果集输出数据

         while (rs.next()) {

            String name =rs.getString("name");

            intage = rs.getInt("age");

            System.out.println("name:" +name + "\tage:" +age);

         }

 

      } catch (ClassNotFoundExceptione) {

         System.out.println("驱动加载失败");

      } catch (SQLExceptione) {

         System.out.println("查询对象创建失败");

      } catch (Exceptione) {

         e.printStackTrace();

      } finally {

         // 6.关闭连接

         if (null !=ps) {

            try {

                ps.close();

            } catch (SQLExceptione) {

                e.printStackTrace();

            }

         }

         if (null !=conn) {

            try {

                conn.close();

            } catch (SQLExceptione) {

                e.printStackTrace();

            }

         }

 

      }

 

   }

原创粉丝点击