java使用JDBC動態(tài)創(chuàng)建數(shù)據(jù)表及SQL預(yù)處理的方法
本文實(shí)例講述了java使用JDBC動態(tài)創(chuàng)建數(shù)據(jù)表及SQL預(yù)處理的方法。分享給大家供大家參考,具體如下:
這兩天由于公司的需求,客戶需要自定義數(shù)據(jù)表的字段,導(dǎo)致每張表的字段都不是固定的而且很難有一個通用的模板去維護(hù),所以就使用JDBC動態(tài)去創(chuàng)建數(shù)據(jù)表,然后通過表的字段動態(tài)添加數(shù)據(jù),數(shù)據(jù)的來源主要是用戶提供的Excel直接導(dǎo)入到數(shù)據(jù)庫中。
如果考慮到字段的類型,可以通過反射的機(jī)制去獲取,現(xiàn)在主要用戶需求就是將數(shù)據(jù)導(dǎo)入到數(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è)置默認(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];
//防止最后一個,
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é)點(diǎn)技巧總結(jié)》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
- MySQL創(chuàng)建數(shù)據(jù)庫和創(chuàng)建數(shù)據(jù)表的操作過程
- mysql如何創(chuàng)建數(shù)據(jù)庫并指定字符集
- MongoDB連接和創(chuàng)建數(shù)據(jù)庫的方法講解
- DataGrip連接Mysql并創(chuàng)建數(shù)據(jù)庫的方法實(shí)現(xiàn)
- MySQL創(chuàng)建數(shù)據(jù)表并建立主外鍵關(guān)系詳解
- 在Mysql上創(chuàng)建數(shù)據(jù)表實(shí)例代碼
- sqlserver2005自動創(chuàng)建數(shù)據(jù)表和自動添加某個字段索引
- MySQL創(chuàng)建數(shù)據(jù)庫和創(chuàng)建數(shù)據(jù)表
相關(guān)文章
關(guān)于@ComponentScan注解的用法及作用說明
這篇文章主要介紹了關(guān)于@ComponentScan注解的用法及作用說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
Mybatis輸入輸出映射及動態(tài)SQL Review
這篇文章主要介紹了Mybatis輸入輸出映射及動態(tài)SQL Review,需要的朋友可以參考下2017-02-02
Java中類與對象的相關(guān)知識點(diǎn)總結(jié)
對象是類實(shí)例化出來的,對象中含有類的屬性,類是對象的抽象,下面這篇文章主要給大家介紹了關(guān)于Java中類與對象的一些相關(guān)知識點(diǎn),需要的朋友可以參考下2021-11-11
Spring Boot利用@Async異步調(diào)用:ThreadPoolTaskScheduler線程池的優(yōu)雅關(guān)閉詳解
這篇文章主要給大家介紹了關(guān)于Spring Boot利用@Async異步調(diào)用:ThreadPoolTaskScheduler線程池的優(yōu)雅關(guān)閉的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05

