码迷,mamicode.com
首页 > 数据库 > 详细

jdbc实例

时间:2015-08-26 21:43:55      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

 class JdbcDemo

{

   pubic static void jdbcTest( String sql)

  {

    Connection con=null;

    PreparedStatement preparedStatement=null;

    ResultSet resultSet=null;

    try{

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

        con=DriverManager.getConnection("jdbc:mysql//locallhost:3306/test?charactorEncoding=utf-8","root","123");

        preparedStatement=con.prepareStatement(sql);//Statement statement=con.createStatement()

        preparedStatement.setString(1,"tom");//给sql语句设置参数

        resultSet=preparedStatement.excuteQuery();

        while(resultSet.next())

        {

          system.out.println(resultSet.getInt("id"));

          System.out.println(resultSet.getString("username"));

        }

      catch( Exception e)

      {

        e.printStackTrace();

      }

      finally

      {

        if(resultSet!=null)

        {

            try{

                resultSet.close();

              }

            catch(SQLException e)

            {

              e.printStackTrace();

            }

        }

 

      

      if(preparedStatement!=null){
        try {
            preparedStatement.close();
          } catch (SQLException e) {
            // TODO Auto-generated catch block
              e.printStackTrace();
              }
          }
      if(connection!=null){
          try {
              connection.close();
            } catch (SQLException e) {
              // TODO Auto-generated catch block
                e.printStackTrace();
            }

      }

      }

  }

}

jdbc实例

标签:

原文地址:http://www.cnblogs.com/chuanqimessi/p/4761467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!