zoukankan      html  css  js  c++  java
  • 20.4 数据库操作

    1、连接数据库
      要访问数据,首先要加载数据库的驱动程序(值需要在第一次访问数据库时加载一次),然后每次访问数据时创建一个Connection对象,接着执行操作数据库的SQL语句,最后在完成数据库操作后销毁前面创建的Connection对象,释放与数据库的连接。
      注意:在本实例中将连接数据库作为单独的一个方法,并以Connection对象作为返回值。这样写的好处是在遇到对数据库卡执行操作的程序时可直接调用Conn类的getConnection()方法获取连接,增加了代码的重用性。
    例子:在项目中创建类Conn,并创建getConnection()方法,获取与MySQL数据库的拦截,在主方法中调用该方法。

     1 import java.sql.*; //导入java.sql包
     2 
     3 public class Conn { // 创建类Conn
     4     Connection con; // 声明Connection对象
     5 
     6     public Connection getConnection() { // 建立返回值为Connection的方法
     7         try { // 加载数据库驱动类
     8             Class.forName("com.mysql.jdbc.Driver");
     9             System.out.println("数据库驱动加载成功");
    10         } catch (ClassNotFoundException e) {
    11             e.printStackTrace();
    12         }
    13         try { // 通过访问数据库的URL获取数据库连接对象
    14             con = DriverManager.getConnection("jdbc:mysql:"
    15                     + "//127.0.0.1:3306/test", "root", "123456");
    16             System.out.println("数据库连接成功");
    17         } catch (SQLException e) {
    18             e.printStackTrace();
    19         }
    20         return con; // 按方法要求返回一个Connection对象
    21     }
    22 
    23     public static void main(String[] args) { // 主方法
    24         Conn c = new Conn(); // 创建本类对象
    25         c.getConnection(); // 调用连接数据库的方法
    26     }
    27 }
    View Code

    2、向数据库发送SQL语句
      在上例中的getConnection()方法,只是获取与数据库的连接,要执行SQL语句首先要获得Statement类对象。通过上例穿件的连接数据库对象con的createStatement()方法可获得Statement对象。
      创建Statement类对象sql如下:
        try{
          Statement sql = con.createStatement();
        }catch (SQLException e){
          e.printStackTrace();
        }

    3、处理查询结果集
      有了Statement对象以后,可调用相应的方法实现对数据库的查询和修改,并将查询的结果集存放在ResulteSet类的对象中。
      获取查询结果集,代码如下:
        ResultSet res = sql.executeQuery("select * from emp");
      运行结果为返回一个ResultSet对象,ResultSet对象一次只可以看到结果集中的一行数据,使用该类的next()方法可将光标从当前位置移向下一行。

    4、顺序查询
      ResultSet类的next()方法的返回值是boolean类型的数据,当游标移动到最后一行之后会返回false。下面的实例就是将数据表emp中的全部信息显示到控制台上。
    例子:本实例在getConnection()方法中获取与数据库的连接,在主方法中将数据表tb_stu中的数据检索出来,保存在便利查询结果集ResulteSet中,并遍历该结果集。

     1 import java.sql.*;
     2 
     3 public class Gradation { // 创建类
     4     static Connection con; // 声明Connection对象
     5     static Statement sql; // 声明Statement对象
     6     static ResultSet res; // 声明ResultSet对象
     7 
     8     public Connection getConnection() { // 连接数据库方法
     9 
    10         try {
    11             Class.forName("com.mysql.jdbc.Driver");
    12             con = DriverManager.getConnection("jdbc:mysql:"
    13                     + "//127.0.0.1:3306/test", "root", "123456");
    14         } catch (Exception e) {
    15             e.printStackTrace();
    16         }
    17         return con; // 返回Connection对象
    18     }
    19 
    20     public static void main(String[] args) { // 主方法
    21         Gradation c = new Gradation(); // 创建本类对象
    22         con = c.getConnection(); // 与数据库建立连接
    23         try {
    24             sql = con.createStatement(); // 实例化Statement对象
    25             // 执行SQL语句,返回结果集
    26             res = sql.executeQuery("select * from tb_stu");
    27             while (res.next()) { // 如果当前语句不是最后一条则进入循环
    28                 String id = res.getString("id"); // 获取列名是"id"的字段值
    29                 // 获取列名是"name"的字段值
    30                 String name = res.getString("name");
    31                 // 获取列名是"sex"的字段值
    32                 String sex = res.getString("sex");
    33                 // 获取列名是"birthday"的字段值
    34                 String birthday = res.getString("birthday");
    35                 System.out.print("编号:" + id); // 将列值输出
    36                 System.out.print(" 姓名:" + name);
    37                 System.out.print(" 性别:" + sex);
    38                 System.out.println(" 生日:" + birthday);
    39             }
    40         } catch (Exception e) {
    41             e.printStackTrace();
    42         }
    43     }
    44 }
    View Code

    5、模糊查询
      SQL语句中提供了LIKE操作符用于模糊查询,可使用“%”来代替0个或多个字符,使用下划线“_”来代替一个字符。例如,在查询姓张的同学的信息时,可使用以下SQL语句:
    select * from tb_stu where name like '张%';
    例子:本实例在getConnection()方法中获取与数据库的连接,在主方法中间数据表tb_stu中姓张的同学的信息检索出来,保存在ResulteSet结果集中,并遍历该集合。

     1 import java.sql.*;
     2 
     3 public class Train { // 创建类Train
     4     static Connection con; // 声明Connection对象
     5     static Statement sql; // 声明Statement对象
     6     static ResultSet res; // 声明ResultSet对象
     7     
     8     public Connection getConnection() { // 与数据库连接方法
     9         try {
    10             Class.forName("com.mysql.jdbc.Driver");
    11             con = DriverManager.getConnection("jdbc:mysql:"
    12                     + "//127.0.0.1:3306/test", "root", "123456");
    13         } catch (Exception e) {
    14             e.printStackTrace();
    15         }
    16         return con; // 返回Connection对象
    17     }
    18     
    19     public static void main(String[] args) { // 主方法
    20         Train c = new Train(); // 创建本类对象
    21         con = c.getConnection(); // 获取与数据库的连接
    22         try { // try语句捕捉异常
    23             sql = con.createStatement(); // 实例化Statement对象
    24             res = sql
    25                     .executeQuery("select * from tb_stu where name like '张%'");// 执行SQL语句
    26             while (res.next()) { // 如果当前记录不是结果集中的最后一条,进入循环体
    27                 String id = res.getString(1); // 获取id字段值
    28                 String name = res.getString("name"); // 获取name字段值
    29                 String sex = res.getString("sex"); // 获取sex字段值
    30                 String birthday = res.getString("birthday"); // 获取birthday字段值
    31                 System.out.print("编号:" + id); // 输出信息
    32                 System.out.print(" 姓名:" + name);
    33                 System.out.print(" 性别:" + sex);
    34                 System.out.println(" 生日:" + birthday);
    35             }
    36         } catch (Exception e) { // 处理异常
    37             e.printStackTrace(); // 输出异常信息
    38         }
    39     }
    40 }
    View Code

    6、预处理语句
      向数据库发送一个SQL语句,数据库中的SQL解释器负责吧SQL语句生成底层的内部命令,然后执行该命令,完成相关的数据操作。如果不断地向数据库提交SQL语句,肯定会增加数据库中SQL解释器的负担,影响执行的速度。
      对于JDBC,可以通过Connection对象的preparedStatement(String sql)方法对SQL语句进行预处理,生成数据库底层的内部命令,并将该命令封装在PreparedStatement对象中,通过调用该对象的相应方法执行底层数据库命令。这样应用程序能针对连接的数据库,实现将SQL语句解释为数据库底层的内部命令,然后让数据库执行这个命令,这样可以减轻数据库的负担,提高访问数据库的速度。
      对SQL进行预处理可以使用通配符“?”来代替任何的字段。如下:
        sql = con.prepareStatement("select * from tb_stu where id=?");
      在执行预处理语句前,必须用相应方法来设置通配符所表示的值。如下:
        sql.setint(1,2);
      上述语句中的“1”表示从左向右的第几个通配符,“2”表示设置的通配符的值。将通配符的值设置为2后,功能等同于:
        sql = con.prepareStatement("selelct * from tb_stu where id=2");
      尽管书写两条语句看似麻烦了一些,但使用预处理语句可使应用程序更容易动态地改变SQL语句中关于字段值条件的设定。
      注意:setXXX()方法为SQL语句中的参数赋值时,建立利用与参数匹配的方法,也可以利用setObject()方法为各种类型的参数赋值。例如:sql.setObject(2,'李丽');
    例子:本实例预处理语句动态地获取指定编号的同学的信息,在此以查询编号为19的同学的信息为例介绍预处理语句的用法。

     1 import java.sql.*;
     2 public class Prep { // 创建类Perp
     3     static Connection con; // 声明Connection对象
     4     static PreparedStatement sql; // 声明预处理对象
     5     static ResultSet res; // 声明结果集对象
     6     public Connection getConnection() { // 与数据库连接方法
     7         try {
     8             Class.forName("com.mysql.jdbc.Driver");
     9             con = DriverManager.getConnection("jdbc:mysql:"
    10                     + "//127.0.0.1:3306/test", "root", "123456");
    11         } catch (Exception e) {
    12             e.printStackTrace();
    13         }
    14         return con; // 返回Connection对象
    15     }
    16     
    17     public static void main(String[] args) { // 主方法
    18         Prep c = new Prep(); // 创建本类对象
    19         con = c.getConnection(); // 获取与数据库的连接
    20         try {
    21             // 实例化预处理对象
    22             sql = con.prepareStatement("select * from tb_stu"
    23                     + " where id = ?");
    24             sql.setInt(1, 4); // 设置参数
    25             res = sql.executeQuery(); // 执行预处理语句
    26             // 如果当前记录不是结果集中最后一行,则进入循环体
    27             while (res.next()) {
    28                 String id = res.getString(1); // 获取结果集中第一列的值
    29                 String name = res.getString("name"); // 获取name列的列值
    30                 String sex = res.getString("sex"); // 获取sex列的列值
    31                 // 获取birthday列的列值
    32                 String birthday = res.getString("birthday");
    33                 System.out.print("编号:" + id); // 输出信息
    34                 System.out.print(" 姓名:" + name);
    35                 System.out.print(" 性别:" + sex);
    36                 System.out.println(" 生日:" + birthday);
    37             }
    38         } catch (Exception e) {
    39             e.printStackTrace();
    40         }
    41     }
    42 }
    View Code

    7、添加、修改、删除记录
      通过SQL语句考科一对数据还行添加、修改和删除操作。可通过PreparedStatement类的指定参数动态对数据表中原有数据进行修改操作,并通过executeUpdate()方法执行更新语句操作。
      注意:executeQuery()方法是在PreparedStatement对象中执行SQL查询,并返回该查询生成的ResultSet对象,而executeUpdate()方法时在PreparedStatement对象中执行SQL语句,该语句必须是一个SQL数据操作语言(Date Maniplation Language,DML)语句,如INSETRT、UPDATE或DELETE语句,或者是无返回内容的SQL语句,如DDL语句。
    例子:本实例通过预处理语句动态地对数据表tb_stu中的数据执行添加、修改、删除操作,并遍历对数据进行操作之前和对数据进行操作之后的tb_stu表中的数据。

     1 import java.sql.*;
     2 
     3 public class Renewal { // 创建类
     4     static Connection con; // 声明Connection对象
     5     static PreparedStatement sql; // 声明PreparedStatement对象
     6     static ResultSet res; // 声明ResultSet对象
     7 
     8     public Connection getConnection() {
     9         try {
    10             Class.forName("com.mysql.jdbc.Driver");
    11             con = DriverManager.getConnection("jdbc:mysql:"
    12                     + "//127.0.0.1:3306/test", "root", "123456");
    13         } catch (Exception e) {
    14             e.printStackTrace();
    15         }
    16         return con;
    17     }
    18 
    19     public static void main(String[] args) {
    20         Renewal c = new Renewal(); // 创建本类对象
    21         con = c.getConnection(); // 调用连接数据库方法
    22         try {
    23             sql = con.prepareStatement("select * from tb_stu"); // 查询数据库
    24             res = sql.executeQuery(); // 执行SQL语句
    25             System.out.println("执行增加、修改、删除前数据:");
    26             while (res.next()) {
    27                 String id = res.getString(1);
    28                 String name = res.getString("name");
    29                 String sex = res.getString("sex");
    30                 String birthday = res.getString("birthday"); // 遍历查询结果集
    31                 System.out.print("编号:" + id);
    32                 System.out.print(" 姓名:" + name);
    33                 System.out.print(" 性别:" + sex);
    34                 System.out.println(" 生日:" + birthday);
    35             }
    36             sql = con.prepareStatement("insert into tb_stu(name,sex,birthday) values(?,?,?)");
    37             sql.setString(1, "张一"); // 预处理添加数据
    38             sql.setString(2, "女");
    39             sql.setString(3, "2012-12-1");
    40             sql.executeUpdate();
    41             sql = con.prepareStatement("update tb_stu set birthday "
    42                     + "= ? where id = ? ");
    43             sql.setString(1, "2012-12-02"); // 更新数据
    44             sql.setInt(2, 1); // 更新数据
    45             sql.executeUpdate();
    46             Statement stmt = con.createStatement();
    47             stmt.executeUpdate("delete from tb_stu where id = 1");
    48             // 查询修改数据后的tb_stu表中数据
    49             sql = con.prepareStatement("select * from tb_stu");
    50             res = sql.executeQuery(); // 执行SQL语句
    51             System.out.println("执行增加、修改、删除后的数据:");
    52             while (res.next()) {
    53                 String id = res.getString(1);
    54                 String name = res.getString("name");
    55                 String sex = res.getString("sex");
    56                 String birthday = res.getString("birthday");
    57                 System.out.print("编号:" + id);
    58                 System.out.print(" 姓名:" + name);
    59                 System.out.print(" 性别:" + sex);
    60                 System.out.println(" 生日:" + birthday);
    61             }
    62         } catch (Exception e) {
    63             e.printStackTrace();
    64         }
    65     }
    66 }
    View Code

    8、参考例子

     1 import java.sql.*;
     2 
     3 public class SearchEmp {
     4 
     5     static Connection con;
     6     static Statement sql;
     7     static ResultSet res;
     8 
     9     public Connection getConnection() {
    10         try {
    11             Class.forName("com.mysql.jdbc.Driver");
    12             con = DriverManager.getConnection(
    13                     "jdbc:mysql://127.0.0.1:3306/test", "root", "123456");
    14         } catch (Exception e) {
    15             e.printStackTrace();
    16         }
    17         return con;
    18     }
    19 
    20     public static void main(String[] args) {
    21         SearchEmp c = new SearchEmp();
    22         con = c.getConnection();
    23         try {
    24             sql = con.createStatement();
    25             res = sql.executeQuery("select * from tb_emp where"
    26                     + " dapt = '销售部'");
    27             while (res.next()) {
    28                 String id = res.getString(1);
    29                 String name = res.getString("name");
    30                 String sex = res.getString("sex");
    31                 String birthday = res.getString("birthday");
    32                 System.out.print("编号:" + id);
    33                 System.out.print(" 姓名:" + name);
    34                 System.out.print(" 性别:" + sex);
    35                 System.out.println(" 生日:" + birthday);
    36             }
    37         } catch (Exception e) {
    38             e.printStackTrace();
    39         }
    40     }
    41 }
    View Code
     1 import java.sql.*;
     2 
     3 public class InsertStu {
     4     
     5     static Connection con;
     6     static PreparedStatement sql;
     7     static ResultSet res;
     8     
     9     public Connection getConnection() {
    10         try {
    11             Class.forName("com.mysql.jdbc.Driver");
    12             con = DriverManager.getConnection("jdbc:mysql:"
    13                     + "//127.0.0.1:3306/test", "root", "123456");
    14         } catch (Exception e) {
    15             e.printStackTrace();
    16         }
    17         return con;
    18     }
    19     
    20     public static void main(String[] args) {
    21         InsertStu c = new InsertStu();
    22         con = c.getConnection();
    23         try {
    24             sql = con.prepareStatement("insert into tb_stu(name,sex,birthday) values(?,?,?)");
    25             sql.setString(1, "李某");
    26             sql.setString(2, "女");
    27             sql.setString(3, "1999-10-20");
    28             sql.executeUpdate();
    29             System.out.println("数据插入成功。");
    30         } catch (SQLException e) {
    31             e.printStackTrace();
    32         }
    33     }
    34 }
    View Code
     1 import java.sql.*;
     2 
     3 public class DeleteStu {
     4     static Connection con;
     5     static PreparedStatement sql;
     6     static ResultSet res;
     7     public Connection getConnection() {
     8         try {
     9             Class.forName("com.mysql.jdbc.Driver");
    10             con = DriverManager.getConnection("jdbc:mysql:"
    11                     + "//127.0.0.1:3306/test", "root", "123456");
    12         } catch (Exception e) {
    13             e.printStackTrace();
    14         }
    15         return con;
    16     }
    17     public static void main(String[] args) {
    18         DeleteStu c = new DeleteStu();
    19         con = c.getConnection();
    20         try {
    21             sql = con.prepareStatement("delete from tb_stu where birthday < ?");
    22             sql.setString(1, "2010-01-01");
    23             sql.executeUpdate();
    24             System.out.println("数据删除完毕");
    25         } catch (SQLException e) {
    26             // TODO 自动生成 catch 块
    27             e.printStackTrace();
    28         }
    29         
    30     }
    31 }
    View Code
  • 相关阅读:
    使用CSS3的appearance属性改变元素的外观
    纯CSS 实现tooltip 内容提示信息效果
    移动端UC /QQ 浏览器的部分私有Meta 属性
    HTML5 的 applicationCache 应用程序缓存离线存储功能与 manifest 文件
    web移动端性能调优及16ms优化
    移动端HTML5资源整理
    js身份证验证-超级准!!!
    编写高效的js/jQuery代码 :rocket:
    html5 摇一摇事件监听
    ios7隐藏系统底部导航
  • 原文地址:https://www.cnblogs.com/studycode/p/9612939.html
Copyright © 2011-2022 走看看