一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - java使用JDBC動(dòng)態(tài)創(chuàng)建數(shù)據(jù)表及SQL預(yù)處理的方法

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

2020-12-18 11:52清墨無痕 Java教程

這篇文章主要介紹了java使用JDBC動(dòng)態(tài)創(chuàng)建數(shù)據(jù)表及SQL預(yù)處理的方法,涉及JDBC操作數(shù)據(jù)庫的連接、創(chuàng)建表、添加數(shù)據(jù)、查詢等相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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)";
          //防止最后一個(gè),
          if(i<length-1){
            sql+=",";
          }
        }
      }
      //拼湊完 建表語句 設(shè)置默認(rèn)字符集
      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];
        //防止最后一個(gè),
        if(i<length-1){
          sql+=",";
        }
      }
      sql+=") values(";
      for(int i=0;i<length;i++){
        sql+="?";
        //防止最后一個(gè),
        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]+" = ? ";
          //防止最后一個(gè),
          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ū)動(dòng)
        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

?
1
2
3
4
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

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

原文鏈接:http://blog.csdn.net/lovelong8808/article/details/44077521

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 精品免费国产 | 全黄h全肉细节修仙玄幻文 全彩调教侵犯h本子全彩妖气he | chinese踩踏调教vk | 2020国语对白露脸 | 热色综合| 国内免费高清视频在线观看 | 草久久网 | 国产精品久久久久影视不卡 | 九九九国产在线 | 欧美一级特黄aaa大片 | 男人影院天堂网址 | 成人嗯啊视频在线观看 | 关晓彤一级做a爰片性色毛片 | 视频免费| 日本小视频网站 | 日本三级欧美三级人妇英文 | 日韩欧美国产一区二区三区 | 超逼网| 国产午夜亚洲精品理论片不卡 | 国产精品亚洲精品日韩已满 | 教师系列 大桥未久在线 | 好大好长好紧爽免费 | 日韩天堂在线 | 高跟丝袜麻麻求我调教 | 亚欧成人一区二区 | 国产一级在线免费观看 | 97自拍视频在线观看 | 午夜大片在线观看 | 免费网址视频在线看 | 恩不要好大好硬好爽3p | 精品推荐国产麻豆剧传媒 | 国产亚洲精品日韩香蕉网 | 女医学护士一级毛片 | 精品免费视在线观看 | chinese男同志videos| 9久re在线观看视频精品 | 亚洲色图二区 | 国产一级片免费视频 | 九九精品视频一区二区三区 | v视界影院.vsjla | 手机在线观看伦理片 |