Home Java javaTutorial Examples of how Java uses JDBC to dynamically create data tables and SQL preprocessing

Examples of how Java uses JDBC to dynamically create data tables and SQL preprocessing

Aug 20, 2017 am 09:42 AM
java jdbc dynamic

The example in this article describes how Java uses JDBC to dynamically create data tables and SQL preprocessing. Share it with everyone for your reference, the details are as follows:

Due to the company's needs in the past two days, customers need to customize the fields of the data table, resulting in the fields of each table being not fixed and difficult to have. A common template is used to maintain, so JDBC is used to dynamically create a data table, and then data is dynamically added through the fields of the table. The source of the data is mainly Excel provided by the user and imported directly into the database.

If you consider the field type, it can be obtained through the reflection mechanism. Now the main user demand is to import data into the database to provide query functions, which cannot be modified, so it is more convenient to directly use the String type to process the data. .


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
public class DataBaseSql {
 //配置文件 读取jdbc的配置文件
 private static ResourceBundle bundle = PropertyResourceBundle.getBundle("db");
 private static Connection conn;
 private static PreparedStatement ps;
  /**
   * 创建表
   * @param tabName 表名称
   * @param tab_fields 表字段
   */
  public static void createTable(String tabName,String[] tab_fields) {
    conn = getConnection();  // 首先要获取连接,即连接到数据库
    try {
      String sql = "create table "+tabName+"(id int auto_increment primary key not null";
      if(tab_fields!=null&&tab_fields.length>0){
        sql+=",";
        int length = tab_fields.length;
        for(int i =0 ;i<length;i++){
          //添加字段
          sql+=tab_fields[i].trim()+" varchar(50)";
          //防止最后一个,
          if(i<length-1){
            sql+=",";
          }
        }
      }
      //拼凑完 建表语句 设置默认字符集
      sql+=")DEFAULT CHARSET=utf8;";
      System.out.println("建表语句是:"+sql);
      ps = conn.prepareStatement(sql);
      ps.executeUpdate(sql);
      ps.close();
      conn.close();  //关闭数据库连接
    } catch (SQLException e) {
      System.out.println("建表失败" + e.getMessage());
    }
  }
  /**
   * 添加数据
   * @param tabName 表名
   * @param fields 参数字段
   * @param data 参数字段数据
   */
  public static void insert(String tabName,String[] fields,String[] data) {
    conn = getConnection();  // 首先要获取连接,即连接到数据库
    try {
      String sql = "insert into "+tabName+"(";
      int length = fields.length;
      for(int i=0;i<length;i++){
        sql+=fields[i];
        //防止最后一个,
        if(i<length-1){
          sql+=",";
        }
      }
      sql+=") values(";
      for(int i=0;i<length;i++){
        sql+="?";
        //防止最后一个,
        if(i<length-1){
          sql+=",";
        }
      }
      sql+=");";
      System.out.println("添加数据的sql:"+sql);
      //预处理SQL 防止注入
      excutePs(sql,length,data);
      //执行
      ps.executeUpdate();
      //关闭流
      ps.close();
      conn.close();  //关闭数据库连接
    } catch (SQLException e) {
      System.out.println("添加数据失败" + e.getMessage());
    }
  }
  /**
   * 查询表 【查询结果的顺序要和数据库字段的顺序一致】
   * @param tabName 表名
   * @param fields 参数字段
   * @param data 参数字段数据
   * @param tab_fields 数据库的字段
   */
  public static String[] query(String tabName,String[] fields,String[] data,String[] tab_fields){
    conn = getConnection();  // 首先要获取连接,即连接到数据库
    String[] result = null;
    try {
      String sql = "select * from "+tabName+" where ";
       int length = fields.length;
       for(int i=0;i<length;i++){
          sql+=fields[i]+" = ? ";
          //防止最后一个,
          if(i<length-1){
            sql+=" and ";
          }
       }
       sql+=";";
       System.out.println("查询sql:"+sql);
      //预处理SQL 防止注入
      excutePs(sql,length,data);
      //查询结果集
      ResultSet rs = ps.executeQuery();
      //存放结果集
      result = new String[tab_fields.length];
      while(rs.next()){
          for (int i = 0; i < tab_fields.length; i++) {
            result[i] = rs.getString(tab_fields[i]);
          }
        }
      //关闭流
      rs.close();
      ps.close();
      conn.close();  //关闭数据库连接
    } catch (SQLException e) {
       System.out.println("查询失败" + e.getMessage());
    }
    return result;
  }
  /**
   * 获取某张表总数
   * @param tabName
   * @return
   */
  public static Integer getCount(String tabName){
    int count = 0;
     conn = getConnection();  // 首先要获取连接,即连接到数据库
     try {
      String sql = "select count(*) from "+tabName+" ;";
       ps = conn.prepareStatement(sql);
       ResultSet rs = ps.executeQuery();
       while(rs.next()){
         count = rs.getInt(1);
        }
       rs.close();
       ps.close();
       conn.close();  //关闭数据库连接
    } catch (SQLException e) {
       System.out.println("获取总数失败" + e.getMessage());
    }
    return count;
  }
  /**
   * 后台分页显示
   * @param tabName
   * @param pageNo
   * @param pageSize
   * @param tab_fields
   * @return
   */
  public static List<String[]> queryForPage(String tabName,int pageNo,int pageSize ,String[] tab_fields){
    conn = getConnection();  // 首先要获取连接,即连接到数据库
    List<String[]> list = new ArrayList<String[]>();
    try {
      String sql = "select * from "+tabName+" LIMIT ?,? ; ";
       System.out.println("查询sql:"+sql);
       //预处理SQL 防止注入
       ps = conn.prepareStatement(sql);
       //注入参数
       ps.setInt(1,pageNo);
       ps.setInt(2,pageSize);
      //查询结果集
      ResultSet rs = ps.executeQuery();
      //存放结果集
      while(rs.next()){
         String[] result = new String[tab_fields.length];
          for (int i = 0; i < tab_fields.length; i++) {
            result[i] = rs.getString(tab_fields[i]);
          }
         list.add(result);
        }
      //关闭流
      rs.close();
      ps.close();
      conn.close();  //关闭数据库连接
    } catch (SQLException e) {
       System.out.println("查询失败" + e.getMessage());
    }
    return list;
  }
  /**
   * 清空表数据
   * @param tabName 表名称
   */
  public static void delete(String tabName){
      conn = getConnection();  // 首先要获取连接,即连接到数据库
      try {
        String sql = "delete from "+tabName+";";
        System.out.println("删除数据的sql:"+sql);
        //预处理SQL 防止注入
        ps = conn.prepareStatement(sql);
        //执行
        ps.executeUpdate();
        //关闭流
        ps.close();
        conn.close();  //关闭数据库连接
      } catch (SQLException e) {
        System.out.println("删除数据失败" + e.getMessage());
      }
  }
  /**
   * 用于注入参数
   * @param ps
   * @param data
   * @throws SQLException
   */
   private static void excutePs(String sql,int length,String[] data) throws SQLException{
     //预处理SQL 防止注入
     ps = conn.prepareStatement(sql);
     //注入参数
     for(int i=0;i<length;i++){
       ps.setString(i+1,data[i]);
     }
   }
   /* 获取数据库连接的函数*/
  private static Connection getConnection() {
    Connection con = null;  //创建用于连接数据库的Connection对象
    try {
        Class.forName(bundle.getString("db.classname"));// 加载Mysql数据驱动
        con = DriverManager.getConnection(bundle.getString("db.url"), bundle.getString("db.username"), bundle.getString("db.password"));// 创建数据连接
    } catch (Exception e) {
        System.out.println("数据库连接失败" + e.getMessage());
    }
    return con;  //返回所建立的数据库连接
  }
  /**
   * 判断表是否存在
   * @param tabName
   * @return
   */
  public static boolean exitTable(String tabName){
    boolean flag = false;
     conn = getConnection();  // 首先要获取连接,即连接到数据库
     try {
       String sql = "select id from "+tabName+";";
       //预处理SQL 防止注入
       ps = conn.prepareStatement(sql);
       //执行
       flag = ps.execute();
       //关闭流
       ps.close();
       conn.close();  //关闭数据库连接
     } catch (SQLException e) {
       System.out.println("删除数据失败" + e.getMessage());
     }
    return flag;
  }
  /**
   * 删除数据表
   * 如果执行成功则返回false
   * @param tabName
   * @return
   */
  public static boolean dropTable(String tabName){
    boolean flag = true;
     conn = getConnection();  // 首先要获取连接,即连接到数据库
       try {
         String sql = "drop table "+tabName+";";
         //预处理SQL 防止注入
         ps = conn.prepareStatement(sql);
         //执行
         flag = ps.execute();
         //关闭流
         ps.close();
         conn.close();  //关闭数据库连接
       } catch (SQLException e) {
         System.out.println("删除数据失败" + e.getMessage());
       }
      return flag;
  }
  /**
   * 测试方法
   * @param args
   */
  public static void main(String[] args) {
    //建表===========================================
    //表名
//    String tabName = "mytable";
    //表字段
//    String[] tab_fields = {"name","password","sex","age"};
    //创建表
//    createTable(tabName, tab_fields);
    //添加===========================================
    //模拟数据
//    String[] data1 = {"jack","123456","男","25"};
//    String[] data2 = {"tom","456789","女","20"};
//    String[] data3 = {"mark","aaa","哈哈","21"};
    //插入数据
//    insert(tabName, tab_fields, data1);
//    insert(tabName, tab_fields, data2);
//    insert(tabName, tab_fields, data3);
    //查询=============================================
//    String[] q_fileds ={"name","sex"};
//    String[] data4 = {"jack","男"};
//
//    String[] result = query(tabName, q_fileds, data4, tab_fields);
//    for (String string : result) {
//      System.out.println("结果:\t"+string);
//    }
    //删除 清空=============================================
//    delete(tabName);
    //是否存在
//    System.out.println(exitTable("mytable"));
    //删除表
//    System.out.println(dropTable("mytable"));
  }
}
Copy after login

Database configuration file db.properties


db.username=root
db.password=root
db.classname=com.mysql.jdbc.Driver
db.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
Copy after login

The above is the detailed content of Examples of how Java uses JDBC to dynamically create data tables and SQL preprocessing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles