zoukankan      html  css  js  c++  java
  • JDBC连接数据库

    配置信息:

    (mysql)

    jdbc.driver.class=com.mysql.jdbc.Driver     (数据库驱动)

    jdbc.connection.url=jdbc:mysql://127.0.0.1:3306/sql       (sql为数据库名)

    jdbc.connection.username=root  

    jdbc.connection.password=123

    (oracle)

    jdbc.driver.class=oracle.jdbc.OracleDriver

    jdbc.connection.url=jdbc:oracle:thin:@127.0.0.1:1521:HELLO

    jdbc.connection.username=c##thie

    jdbc.connection.password=123

    1.加载驱动

    Class.forname(driver);

     

    2.通过DriverManager.getConnection()方法得到与数据库的连接

    Connection conn=DriverManager.getConnection(url,username,password);

     

    3.通过Connection对象得到执行数据库sql语句的对象Statement或者PrepareStatement

    Statement stmt=conn.createStatement();

    或者

    String sql = "insert into card(id,identid,phone,name) values(?,?,?,?);";

    创建prepareStatement时参数是sql语句,要预编译

    PreparedStatement pst=conn.prepareStatement(sql);

    //Statement 相比 PreparedStatement 占用资源小 查询用statement 增删改用PreparedStatement

     

    4.处理结果

    (1)Statement

    String sql="select * from card";

    ResultSet rs=Statement.executeQuery(sql) ;

    //执行Statement的查询方法,参数String类型的sql语句,返回结果集用ResultSet接收之后,

    while(rs.next()) 

    int id=rs.getInt("id"); //  getInt,getString("数据库列名")返回每行的信息

     

    (2)PreparedStatement

    String sql = "insert into card(id,name) values(?,?);";

    sql语句中的参数? 代表要插入的值,顺序不能乱

    PreparedStatement.setInt(1,id);//参数1:表示sql语句中第一个? ,参数2:表示它的值

    PreparedStatement.setString(2,name); 

    int i=PreparedStatement.executeUpdate();

    //执行PreparedStatement的更新方法,返回值是影响数据库表中的行数

     

    5.关闭资源

    先开的最后关,最后开的先关

    if(rs != null)
    rs.close();
    if(pstm!=null) 
    pstm.close();
    if(connection !=null)
    connection.close();

  • 相关阅读:
    Linux systemtap定位系统IO资源使用情况(ok)
    DISK 100% BUSY,谁造成的?(ok)
    容易被误读的IOSTAT
    利用BLKTRACE分析IO性能
    iowait 过高问题的查找及解决linux
    top后台执行显示:top: failed tty get 错误
    Nginx解读内置非默认模块 ngx_http_stub_status_module
    Nginx健康检查模块
    平滑升级你的Nginx
    Practice telephone techniques
  • 原文地址:https://www.cnblogs.com/m97i/p/6902890.html
Copyright © 2011-2022 走看看