##JDBC
**概念:Java DataBase Connectivity
补充:定义了操作所有关系型数据库的规则(接口)。各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口编程,真正执行代码的是数据库驱动中的实现类。
2. 快速入门:
* 步骤:
1. 导入驱动jar包 mysql-connector-java-5.1.37-bin.jar
1.复制mysql-connector-java-5.1.37-bin.jar到项目的libs目录下
2.右键-->Add As Library
2. 注册驱动
3. 获取数据库连接对象 Connection
4. 定义sql
5. 获取执行sql语句的对象 Statement
6. 执行sql,接受返回结果
7. 处理结果
8. 释放资源
3.插入新数据:insert into 表名 values(“”);
4.删除表中部分数据:delete from 表名 where id=名称;
5.建表。
6.resultset应用实例:
package demo; import java.sql.*; public class JDBCDemo05 { public static void main(String[] args) { Connection conn=null; Statement stat=null; ResultSet rs=null; try { Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3309/db2"; conn= DriverManager.getConnection(url,"root","hxj980417"); stat=conn.createStatement(); String sql="select * from account"; rs=stat.executeQuery(sql); while (rs.next()){//遍历查询语句 int id=rs.getInt(1);//查询列数,有列数获得数据 String name=rs.getString("name"); double balance=rs.getDouble(3); System.out.println(id+"\t"+name+"\t"+balance+"\t"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } try { stat.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }
练习:* 定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回。
package lianxi; import java.sql.*; import java.util.ArrayList; import java.util.List; public class demo { public static void findall(){ Connection conn=null; Statement stat=null; ResultSet rs=null; List<Emp> list=new ArrayList<Emp>(); try { Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3309/db2"; conn= DriverManager.getConnection(url,"root","hxj980417"); stat=conn.createStatement(); String sql="select * from emp"; rs=stat.executeQuery(sql); while(rs.next()) { Emp emp = new Emp(); emp.setId(rs.getInt(1)); emp.setEname(rs.getString("ename")); emp.setJob_id(rs.getInt(3)); emp.setMgr(rs.getInt("mgr")); emp.setJoindate(rs.getDate("joindate")); emp.setSalary(rs.getDouble("salary")); emp.setBonus(rs.getDouble("bonus")); emp.setDept_id(rs.getInt("dept_id")); list.add(emp); } for (Emp emp : list) { System.out.println(emp); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { if(rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(stat!=null){ try { stat.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } return; } public static void main(String[] args) { findall(); } }