栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

jdbc连接数据库实例详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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类)

package com.baidu.emp.jdbcTest;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
 
import com.mysql.jdbc.Driver;

public class Test001 {
 
  public static void main(String[] args) throws Exception {
 
    
    // 方法一:
    
    // Driver driver = new Driver();
    // DriverManager.registerDriver(driver);
 
    // 方法二:(推荐使用)
    Class.forName("com.mysql.jdbc.Driver");
 
    
    String url = "jdbc:mysql://localhost:3306/testjdbc";
    String user = "root";
    String password = "root";
    Connection connection = DriverManager.getConnection(url, user, password);
 
    // 创建statement对象
    Statement statement = connection.createStatement();
 
    
    String sql = "select * from test01";
    ResultSet result = statement.executeQuery(sql);
 
    // 遍历结果集
    while (result.next()) {
      String name = result.getString("name");
      int id = result.getInt("id");
      System.out.println(name + "t" + id);
    }
 
    
    result.close();
    statement.close();
    connection.close();
  }
}

防止SQL注入改用prepareStatement

package com.boya.emp.jdbcTest;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Test002 {
 
  public static void main(String[] args) throws Exception {
 
    
    Class.forName("com.mysql.jdbc.Driver");
 
    
    String url = "jdbc:mysql://localhost:3306/testjdbc";
    String user = "root";
    String password = "root";
    Connection connection = DriverManager.getConnection(url, user, password);
 
    // 写SQL 
    String sql = "select * from test01 where id = ?";
    //创建statement对象,预编译
    PreparedStatement statement = connection.prepareStatement(sql);
    //设置参数
    statement.setInt(1, 2);
    
    ResultSet result = statement.executeQuery();
 
    // 遍历结果集
    while (result.next()) {
      String name = result.getString("name");
      int id = result.getInt("id");
      System.out.println(name + "t" + id);
    }
 
    
    result.close();
    statement.close();
    connection.close();
  }
}

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

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

jdbc.properties(配置文件名)

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

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

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

package com.baidu.emp.utils;
 
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
 
import org.junit.Test;
 
 
 
public class JdbcUtils {
 
  static String driverClassName;
  static String url;
  static String user;
  static String password;
 
  static {
    // 创建配置文件对象
    Properties properties = new Properties();
    // 加载配置文件输入流
    InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
    // 重新加载配置文件
    try {
      properties.load(inputStream);
      // 获取配置文件的值
      driverClassName = properties.getProperty("driverName");
      url = properties.getProperty("url");
      user = properties.getProperty("userName");
      password = properties.getProperty("password");
      Class.forName(driverClassName);
 
    } catch (Exception e) {
      // 抛出异常
      throw new RuntimeException(e);
    }
  }
 
  
  @Test
  public void testName() throws Exception {
     
    System.out.println(driverClassName);
  }
  public static Connection getConnection() {
    Connection connection = null;
    try {
      connection = DriverManager.getConnection(url, user, password);
    } catch (SQLException e) {
      // 抛出异常
      throw new RuntimeException(e);
    }
    return connection;
  }
 
  
  public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
 
    try {
      if (resultSet != null) {
 resultSet.close();
      }
      resultSet = null; // 垃圾及时清除
      //注意,不要弄成死循环
      close(connection, statement);
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
 
  }
 
  
  public static void close(Connection connection, PreparedStatement statement) {
 
    try {
      if (connection != null) {
 connection.close();
      }
  
      connection = null;
      if (statement != null) {
 statement.close();
      }
      statement = null;
 
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
 
  }
 
}

测试增删改查:

package com.baidu.emp.jdbcTest;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
 
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 
import com.baidu.emp.utils.JdbcUtils;
 

public class Test003 {
 
  // 初始化值
  Connection connection = null;
  PreparedStatement statement = null;
  ResultSet result = null;
 
  @Before
  public void start() throws Exception {
    // 创建链接
    connection = JdbcUtils.getConnection();
    System.out.println("创建链接");
  }
 
  @After
  public void end() throws Exception {
    // 关闭链接
    JdbcUtils.close(connection, statement, result);
    System.out.println("关闭链接");
  }
   
  
  @Test
  public void add() throws Exception {
    String sql = "insert into test01 values(null,?)";
    statement = connection.prepareStatement(sql);
    statement.setString(1, "李四");
    int result = statement.executeUpdate();
    if (result!=0) {
      System.out.println("添加成功");
    }
  }
  
  @Test
  public void del() throws Exception {
    String sql = "delete from test01 where id =?";
    statement = connection.prepareStatement(sql);
    statement.setInt(1,3);
    int result = statement.executeUpdate();
    if (result!=0) {
      System.out.println("删除成功");
    }
  }
  
  @Test
  public void change() throws Exception {
    String sql = "update test01 set name = ? where id = ?";
    statement = connection.prepareStatement(sql);
    statement.setString(1, "张飞");
    statement.setInt(2, 2);
    int result = statement.executeUpdate();
    if (result!=0) {
      System.out.println("修改成功");
    }
  }
   
  
  @Test
  public void findAll() throws Exception {
    String sql = "select id , name from test01";
    statement = connection.prepareStatement(sql);
    result = statement.executeQuery();
    if (result.next()) {
      System.out.println("查询成功");
    }
  }
   
  
  @Test
  public void findOne() throws Exception {
    String sql = "select id , name from test01 where id = ?";
    statement = connection.prepareStatement(sql);
    statement.setInt(1, 2);
    result = statement.executeQuery();
    if (result.next()) {
      System.out.println("查询成功");
    }
  }
 
}

以上就是相关知识以及相关代码,感谢大家对考高分网的支持。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/138888.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号