JDBC 的使用

网友投稿 243 2022-09-24

JDBC 的使用

一 JDBC 的使用

加载数据库驱动程序 → 建立数据库连接 Connection → 创建执行 SQL 的语句Statement → 处理执行结果 ResultSet → 释放资源

二 通过 Statement 向表中插入数据

2.1注册驱动

Class.forName(“com.mysql.jdbc.Driver”);

2.2获取连接

Connection connection=DriverManager.getConnection(“jdbc:mysql://localhost:3306/cars?useUnicode=true&characterEncoding=utf-8”, “root”, “root”);

2.3执行 SQL

String sql=“insert into car values(default,‘宝马77’)”; statement=connection.createStatement(); int flag=statement.executeUpdate(sql);

2.4释放资源

if(statement!=null) { try { statement.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(); } }

三 通过 Statement 对象修改表中的数据

3.1代码

//更新car表中的数据 public void updateCar() { Connection connection=null; Statement statement=null; try { Class.forName(“com.mysql.jdbc.Driver”); connection=DriverManager.getConnection(“jdbc:mysql://localhost:3306/cars?useUnicode=true&characterEncoding=utf-8”, “root”, “root”); statement=connection.createStatement(); String sql=“update car set car_info=‘大奔a’ where id=56”; int flag=statement.executeUpdate(sql); System.out.println(flag); } catch (Exception e) { // TODO: handle exception }finally { if(statement!=null) { try { statement.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(); } } }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:选车不惑,这4款小型SUV能否让您心动?
下一篇:JDBC3.0 标准中常用接口与类
相关文章

 发表评论

暂时没有评论,来抢沙发吧~