最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java使用JDBC動態(tài)創(chuàng)建數(shù)據(jù)表及SQL預(yù)處理的方法

 更新時間:2017年08月18日 11:16:49   作者:清墨無痕  
這篇文章主要介紹了java使用JDBC動態(tài)創(chuàng)建數(shù)據(jù)表及SQL預(yù)處理的方法,涉及JDBC操作數(shù)據(jù)庫的連接、創(chuàng)建表、添加數(shù)據(jù)、查詢等相關(guān)實現(xiàn)技巧,需要的朋友可以參考下

本文實例講述了java使用JDBC動態(tài)創(chuàng)建數(shù)據(jù)表及SQL預(yù)處理的方法。分享給大家供大家參考,具體如下:

這兩天由于公司的需求,客戶需要自定義數(shù)據(jù)表的字段,導致每張表的字段都不是固定的而且很難有一個通用的模板去維護,所以就使用JDBC動態(tài)去創(chuàng)建數(shù)據(jù)表,然后通過表的字段動態(tài)添加數(shù)據(jù),數(shù)據(jù)的來源主要是用戶提供的Excel直接導入到數(shù)據(jù)庫中。

如果考慮到字段的類型,可以通過反射的機制去獲取,現(xiàn)在主要用戶需求就是將數(shù)據(jù)導入到數(shù)據(jù)庫提供查詢功能,不能修改,所以就直接都使用String類型來處理數(shù)據(jù)更加便捷。

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;
  /**
   * 創(chuàng)建表
   * @param tabName 表名稱
   * @param tab_fields 表字段
   */
  public static void createTable(String tabName,String[] tab_fields) {
    conn = getConnection();  // 首先要獲取連接,即連接到數(shù)據(jù)庫
    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+=",";
          }
        }
      }
      //拼湊完 建表語句 設(shè)置默認字符集
      sql+=")DEFAULT CHARSET=utf8;";
      System.out.println("建表語句是:"+sql);
      ps = conn.prepareStatement(sql);
      ps.executeUpdate(sql);
      ps.close();
      conn.close();  //關(guān)閉數(shù)據(jù)庫連接
    } catch (SQLException e) {
      System.out.println("建表失敗" + e.getMessage());
    }
  }
  /**
   * 添加數(shù)據(jù)
   * @param tabName 表名
   * @param fields 參數(shù)字段
   * @param data 參數(shù)字段數(shù)據(jù)
   */
  public static void insert(String tabName,String[] fields,String[] data) {
    conn = getConnection();  // 首先要獲取連接,即連接到數(shù)據(jù)庫
    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("添加數(shù)據(jù)的sql:"+sql);
      //預(yù)處理SQL 防止注入
      excutePs(sql,length,data);
      //執(zhí)行
      ps.executeUpdate();
      //關(guān)閉流
      ps.close();
      conn.close();  //關(guān)閉數(shù)據(jù)庫連接
    } catch (SQLException e) {
      System.out.println("添加數(shù)據(jù)失敗" + e.getMessage());
    }
  }
  /**
   * 查詢表 【查詢結(jié)果的順序要和數(shù)據(jù)庫字段的順序一致】
   * @param tabName 表名
   * @param fields 參數(shù)字段
   * @param data 參數(shù)字段數(shù)據(jù)
   * @param tab_fields 數(shù)據(jù)庫的字段
   */
  public static String[] query(String tabName,String[] fields,String[] data,String[] tab_fields){
    conn = getConnection();  // 首先要獲取連接,即連接到數(shù)據(jù)庫
    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);
      //預(yù)處理SQL 防止注入
      excutePs(sql,length,data);
      //查詢結(jié)果集
      ResultSet rs = ps.executeQuery();
      //存放結(jié)果集
      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]);
          }
        }
      //關(guān)閉流
      rs.close();
      ps.close();
      conn.close();  //關(guān)閉數(shù)據(jù)庫連接
    } catch (SQLException e) {
       System.out.println("查詢失敗" + e.getMessage());
    }
    return result;
  }
  /**
   * 獲取某張表總數(shù)
   * @param tabName
   * @return
   */
  public static Integer getCount(String tabName){
    int count = 0;
     conn = getConnection();  // 首先要獲取連接,即連接到數(shù)據(jù)庫
     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();  //關(guān)閉數(shù)據(jù)庫連接
    } catch (SQLException e) {
       System.out.println("獲取總數(shù)失敗" + 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();  // 首先要獲取連接,即連接到數(shù)據(jù)庫
    List<String[]> list = new ArrayList<String[]>();
    try {
      String sql = "select * from "+tabName+" LIMIT ?,? ; ";
       System.out.println("查詢sql:"+sql);
       //預(yù)處理SQL 防止注入
       ps = conn.prepareStatement(sql);
       //注入?yún)?shù)
       ps.setInt(1,pageNo);
       ps.setInt(2,pageSize);
      //查詢結(jié)果集
      ResultSet rs = ps.executeQuery();
      //存放結(jié)果集
      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);
        }
      //關(guān)閉流
      rs.close();
      ps.close();
      conn.close();  //關(guān)閉數(shù)據(jù)庫連接
    } catch (SQLException e) {
       System.out.println("查詢失敗" + e.getMessage());
    }
    return list;
  }
  /**
   * 清空表數(shù)據(jù)
   * @param tabName 表名稱
   */
  public static void delete(String tabName){
      conn = getConnection();  // 首先要獲取連接,即連接到數(shù)據(jù)庫
      try {
        String sql = "delete from "+tabName+";";
        System.out.println("刪除數(shù)據(jù)的sql:"+sql);
        //預(yù)處理SQL 防止注入
        ps = conn.prepareStatement(sql);
        //執(zhí)行
        ps.executeUpdate();
        //關(guān)閉流
        ps.close();
        conn.close();  //關(guān)閉數(shù)據(jù)庫連接
      } catch (SQLException e) {
        System.out.println("刪除數(shù)據(jù)失敗" + e.getMessage());
      }
  }
  /**
   * 用于注入?yún)?shù)
   * @param ps
   * @param data
   * @throws SQLException
   */
   private static void excutePs(String sql,int length,String[] data) throws SQLException{
     //預(yù)處理SQL 防止注入
     ps = conn.prepareStatement(sql);
     //注入?yún)?shù)
     for(int i=0;i<length;i++){
       ps.setString(i+1,data[i]);
     }
   }
   /* 獲取數(shù)據(jù)庫連接的函數(shù)*/
  private static Connection getConnection() {
    Connection con = null;  //創(chuàng)建用于連接數(shù)據(jù)庫的Connection對象
    try {
        Class.forName(bundle.getString("db.classname"));// 加載Mysql數(shù)據(jù)驅(qū)動
        con = DriverManager.getConnection(bundle.getString("db.url"), bundle.getString("db.username"), bundle.getString("db.password"));// 創(chuàng)建數(shù)據(jù)連接
    } catch (Exception e) {
        System.out.println("數(shù)據(jù)庫連接失敗" + e.getMessage());
    }
    return con;  //返回所建立的數(shù)據(jù)庫連接
  }
  /**
   * 判斷表是否存在
   * @param tabName
   * @return
   */
  public static boolean exitTable(String tabName){
    boolean flag = false;
     conn = getConnection();  // 首先要獲取連接,即連接到數(shù)據(jù)庫
     try {
       String sql = "select id from "+tabName+";";
       //預(yù)處理SQL 防止注入
       ps = conn.prepareStatement(sql);
       //執(zhí)行
       flag = ps.execute();
       //關(guān)閉流
       ps.close();
       conn.close();  //關(guān)閉數(shù)據(jù)庫連接
     } catch (SQLException e) {
       System.out.println("刪除數(shù)據(jù)失敗" + e.getMessage());
     }
    return flag;
  }
  /**
   * 刪除數(shù)據(jù)表
   * 如果執(zhí)行成功則返回false
   * @param tabName
   * @return
   */
  public static boolean dropTable(String tabName){
    boolean flag = true;
     conn = getConnection();  // 首先要獲取連接,即連接到數(shù)據(jù)庫
       try {
         String sql = "drop table "+tabName+";";
         //預(yù)處理SQL 防止注入
         ps = conn.prepareStatement(sql);
         //執(zhí)行
         flag = ps.execute();
         //關(guān)閉流
         ps.close();
         conn.close();  //關(guān)閉數(shù)據(jù)庫連接
       } catch (SQLException e) {
         System.out.println("刪除數(shù)據(jù)失敗" + e.getMessage());
       }
      return flag;
  }
  /**
   * 測試方法
   * @param args
   */
  public static void main(String[] args) {
    //建表===========================================
    //表名
//    String tabName = "mytable";
    //表字段
//    String[] tab_fields = {"name","password","sex","age"};
    //創(chuàng)建表
//    createTable(tabName, tab_fields);
    //添加===========================================
    //模擬數(shù)據(jù)
//    String[] data1 = {"jack","123456","男","25"};
//    String[] data2 = {"tom","456789","女","20"};
//    String[] data3 = {"mark","aaa","哈哈","21"};
    //插入數(shù)據(jù)
//    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("結(jié)果:\t"+string);
//    }
    //刪除 清空=============================================
//    delete(tabName);
    //是否存在
//    System.out.println(exitTable("mytable"));
    //刪除表
//    System.out.println(dropTable("mytable"));
  }
}

數(shù)據(jù)庫的配置文件 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

更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java+MySQL數(shù)據(jù)庫程序設(shè)計總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java文件與目錄操作技巧匯總》、《Java操作DOM節(jié)點技巧總結(jié)》和《Java緩存操作技巧匯總

希望本文所述對大家java程序設(shè)計有所幫助。

相關(guān)文章

  • Java求兩集合中元素交集的四種方法對比分析

    Java求兩集合中元素交集的四種方法對比分析

    這篇文章主要介紹了Java求兩集合中元素交集的四種方法對比總結(jié),四種求集合中元素交集的方法,按照在處理大量數(shù)據(jù)的效率來看,使用map集合的特性的方法效率最高,之后是使用Java流的方法,其次是使用for循環(huán)和迭代器的方法,需要的朋友可以參考下
    2023-05-05
  • 關(guān)于@ComponentScan注解的用法及作用說明

    關(guān)于@ComponentScan注解的用法及作用說明

    這篇文章主要介紹了關(guān)于@ComponentScan注解的用法及作用說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Mybatis輸入輸出映射及動態(tài)SQL Review

    Mybatis輸入輸出映射及動態(tài)SQL Review

    這篇文章主要介紹了Mybatis輸入輸出映射及動態(tài)SQL Review,需要的朋友可以參考下
    2017-02-02
  • Java中類與對象的相關(guān)知識點總結(jié)

    Java中類與對象的相關(guān)知識點總結(jié)

    對象是類實例化出來的,對象中含有類的屬性,類是對象的抽象,下面這篇文章主要給大家介紹了關(guān)于Java中類與對象的一些相關(guān)知識點,需要的朋友可以參考下
    2021-11-11
  • java LRU算法介紹與用法示例

    java LRU算法介紹與用法示例

    這篇文章主要介紹了java LRU算法,簡單介紹了LRU算法的概念并結(jié)合實例形式分析了LRU算法的具體使用方法,需要的朋友可以參考下
    2017-09-09
  • springboot整合shiro的過程詳解

    springboot整合shiro的過程詳解

    Shiro 是一個強大的簡單易用的 Java 安全框架,主要用來更便捷的 認證,授權(quán),加密,會話管理,這篇文章給大家詳細介紹Shiro 工作原理及架構(gòu)圖,通過實例圖文相結(jié)合給大家介紹的非常詳細,需要的朋友參考下吧
    2021-10-10
  • java中l(wèi)ambda表達式簡單用例

    java中l(wèi)ambda表達式簡單用例

    讓我們從最簡單的例子開始,來學習如何對一個string列表進行排序。我們首先使用Java 8之前的方法來實現(xiàn)
    2016-09-09
  • java獲取http請求的Header和Body的簡單方法

    java獲取http請求的Header和Body的簡單方法

    下面小編就為大家?guī)硪黄猨ava獲取http請求的Header和Body的簡單方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-11-11
  • 關(guān)于Java中的可見性和有序性問題

    關(guān)于Java中的可見性和有序性問題

    這篇文章主要介紹了關(guān)于Java中的可見性和有序性問題,Java在誕生之初就支持多線程,自然也有針對這三者的技術(shù)方案,今天就學習一下Java如何解決其中的可見性和有序性導致的問題,需要的朋友可以參考下
    2023-08-08
  • Spring Boot利用@Async異步調(diào)用:ThreadPoolTaskScheduler線程池的優(yōu)雅關(guān)閉詳解

    Spring Boot利用@Async異步調(diào)用:ThreadPoolTaskScheduler線程池的優(yōu)雅關(guān)閉詳解

    這篇文章主要給大家介紹了關(guān)于Spring Boot利用@Async異步調(diào)用:ThreadPoolTaskScheduler線程池的優(yōu)雅關(guān)閉的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧
    2018-05-05

最新評論

福州市| 合川市| 江油市| 阿鲁科尔沁旗| 定襄县| 南投县| 盐城市| 郓城县| 莫力| 共和县| 尼木县| 卢氏县| 德昌县| 正定县| 遂川县| 石棉县| 潼关县| 乌兰浩特市| 湾仔区| 木里| 定南县| 合肥市| 和田市| 汪清县| 哈尔滨市| 江源县| 曲周县| 无锡市| 根河市| 大方县| 安陆市| 当雄县| 逊克县| 泸西县| 巴林左旗| 镇赉县| 九龙县| 根河市| 资源县| 夏邑县| 安塞县|