JDBC基础


连接数据库的步骤:

1、  注册驱动(“com.mysql.jdbc.Driver”)

2、  建立连接(Connection)(“jdbc:mysql://localhost:3306/jdbc”)

3、  创建执行SQL的语句(Statement

4、  执行语句

5、  处理执行结果(ResultSet

6、  释放资源

注册驱动:DriverManager.registerDriver(“new com.mysql.jdbc.Driver( )”);

                     System.setProperty(“jdbc.drivers”,”com.mysql.jdbc.Driver”);

              Class.forName(“com.mysql.jdbc.Driver”);--à建议使用不会对具体的类产生依赖

封装注册、建立连接、释放资源:

publicfinalclass JDBCUtils {

    privatestaticfinal Stringurl ="jdbc:mysql://localhost:3306/jdbc";

    privatestaticfinal Stringuser ="root";

    privatestaticfinal Stringpassword ="admin";

    private JDBCUtils() {

    }

    static {

       try {

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

       } catch (ClassNotFoundException e) {

          thrownew ExceptionInInitializerError(e);

       }

    }

    publicstatic Connection getConnection()throws SQLException {

       return DriverManager.getConnection(url,user,password);

    }

    publicstaticvoid free(Connection conn, Statement st, ResultSet rs) {

       try {

          if (rs !=null) {

             rs.close();

          }

       } catch (SQLException e) {

          e.printStackTrace();

       } finally {

          try {

             if (st !=null) {

                 st.close();

             }

          }catch (SQLException e) {

             e.printStackTrace();

          }finally {

             try {

                 if (conn !=null) {

                    conn.close();

                 }

             }catch (SQLException e1) {

                 e1.printStackTrace();

             }

          }

       }

    }

}

对数据库的操作:CcreateRreadUupdateDdelete

SQL注入:(PreparedStatementStatement

    SQL中包含特殊字符或SQL的关键字(如:‘or 1 or’)时Statement将出现不可预料的结果(出现异常或者查询的结果不正确),可用PreparedStatement来解决;

    PreparedStatement相对于Statement的优点

1、 没有SQL注入的问题

2、 Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出

3、 数据库和驱动可以对PreparedStatement进行优化(只有在相关联的数据库连接没有关闭的情况下有效)

JDBC访问日期的问题:

publicclass CRUD {

    publicstaticvoid main(String[] args)throws Exception{

       create("tianjian",new Date(),799.0f);

    }

    publicstaticvoidcreate(String name,Date birthday,float money)throws Exception{

       Connection conn=null;

       PreparedStatement ps=null;

       ResultSet rs=null;

       try{

          conn=JDBCUtils.getConnection();

String sql="insert into user(name,birthday,money)values(?,?,?)";

          ps=conn.prepareStatement(sql);

          ps.setString(1, name);

          ps.setDate(2,new java.sql.Date(birthday.getTime()));

          ps.setFloat(3, money);

          ps.executeUpdate();

       }

       finally{

          JDBCUtils.free(conn, ps, rs);

       }

    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值