zoukankan      html  css  js  c++  java
  • jdbc链接数据库

     

    JDBC简介

    JDBC全称为:Java Data Base Connectivity (java数据库连接),可以为多种数据库提供填统一的访问。JDBC是sun开发的一套数据库访问编程接口,是一种SQL级的API。它是由java语言编写完成,所以具有很好的跨平台特性,使用JDBC编写的数据库应用程序可以在任何支持java的平台上运行,而不必在不同的平台上编写不同的应用程序。

    JDBC编程步骤

    (1)加载驱动程序:

      下载驱动包 : http://dev.mysql.com/downloads/connector/j/

    解压,得到 jar文件。将该文件复制到Java工程目录Java Resources/Libraries/ 下,→ buildpath 。

    (2)获得数据库连接

    (3)创建Statement对象:

    (4)向数据库发送SQL命令

    (5)处理数据库的返回结果(ResultSet类)

     1 package com.baidu.emp.jdbcTest;
     2 
     3 import java.sql.Connection;
     4 import java.sql.DriverManager;
     5 import java.sql.ResultSet;
     6 import java.sql.Statement;
     7 
     8 import com.mysql.jdbc.Driver;
     9 /**
    10  * 开始使用jdbc连接数据库
    11  * @author Admin
    12  *
    13  */
    14 public class Test001 {
    15 
    16     public static void main(String[] args) throws Exception {
    17 
    18         /**
    19          * 加载驱动
    20          */
    21         // 方法一:
    22         /*
    23          * import java.sql.DriverManager; import com.mysql.jdbc.Driver;
    24          */
    25         // Driver driver = new Driver();
    26         // DriverManager.registerDriver(driver);
    27 
    28         // 方法二:(推荐使用)
    29         Class.forName("com.mysql.jdbc.Driver");
    30 
    31         /**
    32          * 创建链接
    33          */
    34         String url = "jdbc:mysql://localhost:3306/testjdbc";
    35         String user = "root";
    36         String password = "root";
    37         Connection connection = DriverManager.getConnection(url, user, password);
    38 
    39         // 创建statement对象
    40         Statement statement = connection.createStatement();
    41 
    42         /**
    43          * 执行SQL,获取结果集
    44          */
    45         String sql = "select * from test01";
    46         ResultSet result = statement.executeQuery(sql);
    47 
    48         // 遍历结果集
    49         while (result.next()) {
    50             String name = result.getString("name");
    51             int id = result.getInt("id");
    52             System.out.println(name + "	" + id);
    53         }
    54 
    55         /**
    56          * 关闭链接,释放资源
    57          */
    58         result.close();
    59         statement.close();
    60         connection.close();
    61     }
    62 }

    防止SQL注入改用prepareStatement

     1 package com.boya.emp.jdbcTest;
     2 
     3 import java.sql.Connection;
     4 import java.sql.DriverManager;
     5 import java.sql.PreparedStatement;
     6 import java.sql.ResultSet;
     7 /**
     8  * SQL注入,使用prepareStatement对象进行预编译
     9  * @author Admin
    10  *
    11  */
    12 public class Test002 {
    13 
    14     public static void main(String[] args) throws Exception {
    15 
    16         /**
    17          * 加载驱动
    18          */
    19         Class.forName("com.mysql.jdbc.Driver");
    20 
    21         /**
    22          * 创建链接
    23          */
    24         String url = "jdbc:mysql://localhost:3306/testjdbc";
    25         String user = "root";
    26         String password = "root";
    27         Connection connection = DriverManager.getConnection(url, user, password);
    28 
    29         // 写SQL 
    30         String sql = "select * from test01 where id = ?";
    31         //创建statement对象,预编译
    32         PreparedStatement statement = connection.prepareStatement(sql);
    33         //设置参数
    34         statement.setInt(1, 2);
    35         /**
    36          * 执行SQL,获取结果集
    37          */
    38         ResultSet result = statement.executeQuery();
    39 
    40         // 遍历结果集
    41         while (result.next()) {
    42             String name = result.getString("name");
    43             int id = result.getInt("id");
    44             System.out.println(name + "	" + id);
    45         }
    46 
    47         /**
    48          * 关闭链接,释放资源
    49          */
    50         result.close();
    51         statement.close();
    52         connection.close();
    53     }
    54 } 
    View Code

    进行代码优化,设置配置文件,工具类,实现增删该查

     增加配置文件方便修改数据库,用户登录。。。

    jdbc.properties(配置文件名)

    1 driverName=com.mysql.jdbc.Driver
    2 url=jdbc:mysql://localhost:3306/testjdbc
    3 userName=root
    4 password=root

    注意写配置文件时中间不可以有空格,引号之类的

    工具类:增强了代码的复用性

      1 package com.baidu.emp.utils;
      2 
      3 import java.io.InputStream;
      4 import java.sql.Connection;
      5 import java.sql.DriverManager;
      6 import java.sql.PreparedStatement;
      7 import java.sql.ResultSet;
      8 import java.sql.SQLException;
      9 import java.util.Properties;
     10 
     11 import org.junit.Test;
     12 
     13 
     14 
     15 public class JdbcUtils {
     16 
     17     static String driverClassName;
     18     static String url;
     19     static String user;
     20     static String password;
     21 
     22     static {
     23         // 创建配置文件对象
     24         Properties properties = new Properties();
     25         // 加载配置文件输入流
     26         InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
     27         // 重新加载配置文件
     28         try {
     29             properties.load(inputStream);
     30             // 获取配置文件的值
     31             driverClassName = properties.getProperty("driverName");
     32             url = properties.getProperty("url");
     33             user = properties.getProperty("userName");
     34             password = properties.getProperty("password");
     35             Class.forName(driverClassName);
     36 
     37         } catch (Exception e) {
     38             // 抛出异常
     39             throw new RuntimeException(e);
     40         }
     41     }
     42 
     43     /**
     44      * 获取连接
     45      */
     46     @Test
     47     public void testName() throws Exception {
     48         
     49         System.out.println(driverClassName);
     50     }
     51     public static Connection getConnection() {
     52         Connection connection = null;
     53         try {
     54             connection = DriverManager.getConnection(url, user, password);
     55         } catch (SQLException e) {
     56             // 抛出异常
     57             throw new RuntimeException(e);
     58         }
     59         return connection;
     60     }
     61 
     62     /**
     63      * 关闭链接,释放资源
     64      */
     65     public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
     66 
     67         try {
     68             if (resultSet != null) {
     69                 resultSet.close();
     70             }
     71             resultSet = null; // 垃圾及时清除
     72             //注意,不要弄成死循环
     73             close(connection, statement);
     74         } catch (SQLException e) {
     75             throw new RuntimeException(e);
     76         }
     77 
     78     }
     79 
     80     /**
     81      * 增删改释放资源
     82      */
     83     public static void close(Connection connection, PreparedStatement statement) {
     84 
     85         try {
     86             if (connection != null) {
     87                 connection.close();
     88             }
     89                 
     90             connection = null;
     91             if (statement != null) {
     92                 statement.close();
     93             }
     94             statement = null;
     95 
     96         } catch (SQLException e) {
     97             throw new RuntimeException(e);
     98         }
     99 
    100     }
    101 
    102 }
    View Code

    测试增删改查:

      1 package com.baidu.emp.jdbcTest;
      2 
      3 import java.sql.Connection;
      4 import java.sql.PreparedStatement;
      5 import java.sql.ResultSet;
      6 
      7 import org.junit.After;
      8 import org.junit.Before;
      9 import org.junit.Test;
     10 
     11 import com.baidu.emp.utils.JdbcUtils;
     12 
     13 /**
     14  * 使用jdbcUtils连接数据库进行增删改查
     15  * 
     16  * @author Admin
     17  *
     18  */
     19 public class Test003 {
     20 
     21     // 初始化值
     22     Connection connection = null;
     23     PreparedStatement statement = null;
     24     ResultSet result = null;
     25 
     26     @Before
     27     public void start() throws Exception {
     28         // 创建链接
     29         connection = JdbcUtils.getConnection();
     30         System.out.println("创建链接");
     31     }
     32 
     33     @After
     34     public void end() throws Exception {
     35         // 关闭链接
     36         JdbcUtils.close(connection, statement, result);
     37         System.out.println("关闭链接");
     38     }
     39     
     40     /**
     41      *插入数据
     42      * @throws Exception
     43      */
     44     @Test
     45     public void add() throws Exception {
     46         String sql = "insert into test01 values(null,?)";
     47         statement = connection.prepareStatement(sql);
     48         statement.setString(1, "李四");
     49         int result = statement.executeUpdate();
     50         if (result!=0) {
     51             System.out.println("添加成功");
     52         }
     53     }
     54     /**
     55      * 删除数据
     56      * @throws Exception
     57      */
     58     @Test
     59     public void del() throws Exception {
     60         String sql = "delete from test01 where id =?";
     61         statement = connection.prepareStatement(sql);
     62         statement.setInt(1,3);
     63         int result = statement.executeUpdate();
     64         if (result!=0) {
     65             System.out.println("删除成功");
     66         }
     67     }
     68     /**
     69      * 修改数据
     70      * @throws Exception
     71      */
     72     @Test
     73     public void change() throws Exception {
     74         String sql = "update test01 set name = ? where id = ?";
     75         statement = connection.prepareStatement(sql);
     76         statement.setString(1, "张飞");
     77         statement.setInt(2, 2);
     78         int result = statement.executeUpdate();
     79         if (result!=0) {
     80             System.out.println("修改成功");
     81         }
     82     }
     83     
     84     /**
     85      * 查询全部数据
     86      * @throws Exception
     87      */
     88     @Test
     89     public void findAll() throws Exception {
     90         String sql = "select id , name from test01";
     91         statement = connection.prepareStatement(sql);
     92         result = statement.executeQuery();
     93         if (result.next()) {
     94             System.out.println("查询成功");
     95         }
     96     }
     97     
     98     /**
     99      * 条件查询数据
    100      * @throws Exception
    101      */
    102     @Test
    103     public void findOne() throws Exception {
    104         String sql = "select id , name from test01 where id = ?";
    105         statement = connection.prepareStatement(sql);
    106         statement.setInt(1, 2);
    107         result = statement.executeQuery();
    108         if (result.next()) {
    109             System.out.println("查询成功");
    110         }
    111     }
    112 
    113 }

    希望能给大家一个参考,也希望大家多多支持我。

      

  • 相关阅读:
    [二叉查找树] 1115. Counting Nodes in a BST (30)
    [最小生成树] 继续畅通工程
    [最小生成树] 畅通工程
    [最小生成树] 还是畅通工程
    [图算法] 1030. Travel Plan (30)
    [图算法] 1003. Emergency (25)
    [并查集] More is Better
    [并查集] How Many Tables
    [并查集] 畅通工程
    [并查集] 通信系统
  • 原文地址:https://www.cnblogs.com/kaikai-2018/p/10392646.html
Copyright © 2011-2022 走看看