JDBC的简单介绍

来源:互联网 发布:玄机科技工资 知乎 编辑:程序博客网 时间:2024/06/15 07:04

简单的JDBC实例,主要是使用JDBC连接MySQL数据库,然后对数据库进行一些基本的增删改查操作。

1,设计数据表

先设计一张数据表,用户保存用户信息,建表语句如下:

CREATE TABLE `person` ( `id` int(11) NOT NULL, `name` text NOT NULL, `phone` varchar(255) CHARACTER SET latin1 DEFAULT NULL, `age` int(11) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

在person表中定义了几个字段,分别是id,name,phone,age,其中id是主键,是自增长,name表示用户名,phone是用户的手机,age是用户的年龄。

预先在数据库中插入几条数据,数据如下:

这里写图片描述

2,定义实体类

定义一个Bean,与数据库表中的各个字段对应:

public class Person {private int id;private String name;private String phone;private int age;public int getId() {    return id;}public void setId(int id) {    this.id = id;}public String getName() {    return name;}public void setName(String name){    this.name = name;}public String getPhone() {    return phone;}public void setPhone(String phone) {    this.phone = phone;}public int getAge() {    return age;}public void setAge(int age) {    this.age = age;}public String toString() {    return "Person [id=" + id + ", name=" + name + ", phone=" + phone            + ", age=" + age + "]";}public Person(int id, String name, String phone, int age) {    super();    this.id = id;    this.name = name;    this.phone = phone;    this.age = age;}public Person() {    super();    // TODO Auto-generated constructor stub}}

3,定义数据库连接类 
定义一个数据看连接类,用户获取mysql的连接

public class DBUtil {private static String URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8";private static String Driver = "com.mysql.jdbc.Driver";private static String user = "root";private static String password = "";public static Connection connectDB() throws Exception {    Class.forName(Driver);    Connection conn = DriverManager.getConnection(URL, user, password);    return conn;}}

Mysql的JDBC URL编写方式为:jdbc:mysql//主机名称:连接端口/数据库名称?参数=值,为了避免中文乱码要指定useUnicode和characterEncoding.因为连接的是Mysql数据库,所以程序一开始需要加载Mysql的数据库驱动,然后通过DriverManager.getConnection(String URL)方法获取数据库的连接。

4,实现数据库的增删改查

获取了数据库的连接之后,就可以操作数据库了,下面分别实现数据库的增删改查操作,定义了一个PersonDao类用于操作数据库.

1)查询

先看查询操作,在PersonDao中定义了一个queryAll()方法:

public List<Person> queryAll() throws Exception {    Connection conn = DBUtil.connectDB();    String sql = "SELECT * FROM person";    List<Person> personList = new ArrayList<Person>();    Statement stmt = conn.createStatement();    ResultSet rs = stmt.executeQuery(sql);    while (rs.next()) {        Person person = new Person();        person.setId(rs.getInt("id"));        person.setName(rs.getString("name"));        person.setPhone(rs.getString("phone"));        person.setAge(rs.getInt("age"));        personList.add(person);    }    return personList;}

这里使用conn.createStatement()方法获取一个Statement对象,这个对象里面有很多方法可以操作数据库,使用executeQuery(sql)执行查询操作,查询结果为一个结果集ResultSet,可以通过这个结果集获取相关信息。

定义main函数:

public static void main(String[] args){    PersonDao dao = new PersonDao();    try {        List<Person> personList = dao.queryAll();        for (Person person : personList) {            System.out.println(person);        }    } catch (Exception e) {        e.printStackTrace();    }   }

执行结果:

Person [id=10, name=胡春, phone=18229096647, age=34]Person [id=11, name=王菲, phone=18229096640, age=21]Person [id=12, name=刘明, phone=18229096649, age=22]Person [id=13, name=白云, phone=18229096646, age=25]Person [id=15, name=黄土, phone=18229096644, age=20]

根据条件查询,定义一个queryByParams方法:

public List<Person> queryParams(List<Map<String, Object>> params) throws Exception {    Connection conn = DBUtil.connectDB();    String sql = "SELECT * FROM person WHERE 26=26";    System.out.println(sql.toString());    List<Person> personList = new ArrayList<Person>();    Statement stmt = conn.createStatement();     ResultSet rs = stmt.executeQuery(sql.toString());    while (rs.next()) {        Person person = new Person();        person.setId(rs.getInt("id"));        person.setName(rs.getString("name"));        person.setPhone(rs.getString("phone"));        person.setAge(rs.getInt("age"));        personList.add(person);    }    return personList; }

这个方法自由选择查询的条件,只需要向方法中传入一个条件List即可,这些条件都市有Map组成,每一个Map包含三个元素,col表示查询列,rel表示查询条件的关系,value是指查询条件的值。

PersonDao dao = new PersonDao();List<Map<String, Object>>  params = new ArrayList<Map<String,Object>>();Map<String, Object>  param1 = new  HashMap<String, Object>();    param1.put("id", "20");    param1.put("name", "jaerk");    param1.put("phone", "13266512345");    param1.put("age", "%26%");params.add(param1);Map<String, Object>  param2 = new  HashMap<String, Object>();param2.put("id", "290");    param2.put("name", "jark");    param2.put("phone", "13666512345");    param2.put("age", 26);    params.add(param2);    try {    List<Person> personList = dao.queryParams(params);        for (Person person : personList) {            System.out.println(person);    }} catch (Exception e) {    e.printStackTrace();    }    }

2增加

现在在PersonDao中写一个addPerson方法用于新增一条信息:

public void addPerson(Person person) throws Exception {    Connection conn = DBUtil.connectDB();    String sql = "INSERT INTO person(id, name, phone, age)"                    + " VALUES(?, ?, ?, ?)";          PreparedStatement psmt = conn.prepareStatement(sql);        psmt.setInt(1, person.getId());    psmt.setString(2, person.getName());    psmt.setString(3, person.getPhone());    psmt.setInt(4, person.getAge());    psmt.execute();    conn.close();}

这个方法使用conn.prepareStatement(sql)获取一个PreparedStatement对象,使用这个方法可以传入带参数的SQL语句,而参数的值可以通过PreparedStatement.setXXX(index,value)方法指定,其中xxx为各种不同的类型,index指定第几个参数,value指定了带参数的值,便可以执行excute()方法执行sql语句了。

 PersonDao dao = new PersonDao();    Person person = new Person();    person.setName("黑风");           person.setPhone("18229096642");    person.setAge(20);    person.setId(16);    try {        dao.addPerson(person);    } catch (Exception e) {        e.printStackTrace();    }    }

执行后再查看数据库,发现”黑风”用户插入成功

这里写图片描述

3:删除

接下来写一个删除的方法,根据用户的id来删除数据:

public void deleteUser(int id) throws Exception {    Connection conn = DBUtil.connectDB();    String sql = "DELETE FROM person WHERE id = ?";    PreparedStatement psmt = conn.prepareStatement(sql);    psmt.setInt(1, id);    psmt.execute();    }

然后写一个main方法来验证:

PersonDao dao = new PersonDao(); try {    dao.deleteUser(26);    } catch (Exception e) {        e.printStackTrace();    }

删除id为26的用户,运行后查看数据库:

这里写图片描述

4:更新数据库

最后来看一下更新数据库:

 public void updatePerson(Person person) throws Exception {    Connection conn = DBUtil.connectDB();    String sql = "UPDATE person SET name=?, phone=?, age=?"                  + " WHERE id=?";    PreparedStatement pstmt = conn.prepareStatement(sql);    pstmt.setInt(4, person.getId());    pstmt.setString(1, person.getName());    pstmt.setString(2, person.getPhone());    pstmt.setInt(3, person.getAge());    pstmt.executeUpdate();    conn.close();}

从SQL语句中可以看出更新的也就是根据用户id进行选择性的更新。 
写一个main方法验证:

 PersonDao dao = new PersonDao(); Person person = new Person();    person.setName("黑风");           person.setPhone("18229096642");    person.setAge(26);    person.setId(18);try {        dao.updatePerson(person);    } catch (Exception e) {        e.printStackTrace();    }}

这个方法里将用户名为黑风的用户年龄改为26岁,执行程序,运行后查看数据库:

这里写图片描述

可以看到用户的年龄变成了26,更新成功。

三,总结 
使用JDBC连接Mysql数据库并进行基本的增删改查就已经完成了,这些只是最简单的数据库操作,实际开发过程中操作数据库比这些复杂多了,包括事务处理,存储过程等等,就需要使用JDBC更高级的功能了。

原创粉丝点击