简单的连接数据库标准步骤

来源:互联网 发布:java并发编程艺术 编辑:程序博客网 时间:2024/06/05 05:07

1:方法没有封装的情况下:

public class ConnectionDemo{

   public static void main(String[] args){

    //1:设置参数

    String url="jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=utf8";

   String user="root";

  String pwd="123456";

 Connection conn=null;

 PreparedStatement pstmt=null;

 ResultSet rs=null;

 try{

    //    2加载驱动

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

    //  3 获取Connection 对象

    conn=DriverManager.getConnection(url,user,pwd);

   //  4发送sql 语句

    String sql="select * from user where id=?";

   pstmt=conn.prepareStatement(sql);

      //5设置参数

   pstmt.setNameid(1);

   pstmt.setName("lisi");

       //6执行

  rs.pstmt.executeQuery();

  //7取出结果

   while(rs.next()){

        int  use_id=rs.getInt(); //第一列

       String use_name=rs.getString("usr_name“”);

     system.out.println(use_id+"\t"+use_name);

   }

  }catch(ClassNotFoundException e){

      e.printStackTrace();

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

 }catch(SQLException e){

     e.printStackTrace();

    System.out.println("获取连接对象失败!");

          }

      }

   }

}