java使用JDBC動態(tài)創(chuàng)建數(shù)據表及SQL預處理的方法
本文實例講述了java使用JDBC動態(tài)創(chuàng)建數(shù)據表及SQL預處理的方法。分享給大家供大家參考,具體如下:
這兩天由于公司的需求,客戶需要自定義數(shù)據表的字段,導致每張表的字段都不是固定的而且很難有一個通用的模板去維護,所以就使用JDBC動態(tài)去創(chuàng)建數(shù)據表,然后通過表的字段動態(tài)添加數(shù)據,數(shù)據的來源主要是用戶提供的Excel直接導入到數(shù)據庫中。
如果考慮到字段的類型,可以通過反射的機制去獲取,現(xiàn)在主要用戶需求就是將數(shù)據導入到數(shù)據庫提供查詢功能,不能修改,所以就直接都使用String類型來處理數(shù)據更加便捷。
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ù)據庫
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(); //關閉數(shù)據庫連接
} catch (SQLException e) {
System.out.println("建表失敗" + e.getMessage());
}
}
/**
* 添加數(shù)據
* @param tabName 表名
* @param fields 參數(shù)字段
* @param data 參數(shù)字段數(shù)據
*/
public static void insert(String tabName,String[] fields,String[] data) {
conn = getConnection(); // 首先要獲取連接,即連接到數(shù)據庫
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ù)據的sql:"+sql);
//預處理SQL 防止注入
excutePs(sql,length,data);
//執(zhí)行
ps.executeUpdate();
//關閉流
ps.close();
conn.close(); //關閉數(shù)據庫連接
} catch (SQLException e) {
System.out.println("添加數(shù)據失敗" + e.getMessage());
}
}
/**
* 查詢表 【查詢結果的順序要和數(shù)據庫字段的順序一致】
* @param tabName 表名
* @param fields 參數(shù)字段
* @param data 參數(shù)字段數(shù)據
* @param tab_fields 數(shù)據庫的字段
*/
public static String[] query(String tabName,String[] fields,String[] data,String[] tab_fields){
conn = getConnection(); // 首先要獲取連接,即連接到數(shù)據庫
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(); //關閉數(shù)據庫連接
} 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ù)據庫
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(); //關閉數(shù)據庫連接
} 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ù)據庫
List<String[]> list = new ArrayList<String[]>();
try {
String sql = "select * from "+tabName+" LIMIT ?,? ; ";
System.out.println("查詢sql:"+sql);
//預處理SQL 防止注入
ps = conn.prepareStatement(sql);
//注入參數(shù)
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(); //關閉數(shù)據庫連接
} catch (SQLException e) {
System.out.println("查詢失敗" + e.getMessage());
}
return list;
}
/**
* 清空表數(shù)據
* @param tabName 表名稱
*/
public static void delete(String tabName){
conn = getConnection(); // 首先要獲取連接,即連接到數(shù)據庫
try {
String sql = "delete from "+tabName+";";
System.out.println("刪除數(shù)據的sql:"+sql);
//預處理SQL 防止注入
ps = conn.prepareStatement(sql);
//執(zhí)行
ps.executeUpdate();
//關閉流
ps.close();
conn.close(); //關閉數(shù)據庫連接
} catch (SQLException e) {
System.out.println("刪除數(shù)據失敗" + e.getMessage());
}
}
/**
* 用于注入參數(shù)
* @param ps
* @param data
* @throws SQLException
*/
private static void excutePs(String sql,int length,String[] data) throws SQLException{
//預處理SQL 防止注入
ps = conn.prepareStatement(sql);
//注入參數(shù)
for(int i=0;i<length;i++){
ps.setString(i+1,data[i]);
}
}
/* 獲取數(shù)據庫連接的函數(shù)*/
private static Connection getConnection() {
Connection con = null; //創(chuàng)建用于連接數(shù)據庫的Connection對象
try {
Class.forName(bundle.getString("db.classname"));// 加載Mysql數(shù)據驅動
con = DriverManager.getConnection(bundle.getString("db.url"), bundle.getString("db.username"), bundle.getString("db.password"));// 創(chuàng)建數(shù)據連接
} catch (Exception e) {
System.out.println("數(shù)據庫連接失敗" + e.getMessage());
}
return con; //返回所建立的數(shù)據庫連接
}
/**
* 判斷表是否存在
* @param tabName
* @return
*/
public static boolean exitTable(String tabName){
boolean flag = false;
conn = getConnection(); // 首先要獲取連接,即連接到數(shù)據庫
try {
String sql = "select id from "+tabName+";";
//預處理SQL 防止注入
ps = conn.prepareStatement(sql);
//執(zhí)行
flag = ps.execute();
//關閉流
ps.close();
conn.close(); //關閉數(shù)據庫連接
} catch (SQLException e) {
System.out.println("刪除數(shù)據失敗" + e.getMessage());
}
return flag;
}
/**
* 刪除數(shù)據表
* 如果執(zhí)行成功則返回false
* @param tabName
* @return
*/
public static boolean dropTable(String tabName){
boolean flag = true;
conn = getConnection(); // 首先要獲取連接,即連接到數(shù)據庫
try {
String sql = "drop table "+tabName+";";
//預處理SQL 防止注入
ps = conn.prepareStatement(sql);
//執(zhí)行
flag = ps.execute();
//關閉流
ps.close();
conn.close(); //關閉數(shù)據庫連接
} catch (SQLException e) {
System.out.println("刪除數(shù)據失敗" + 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ù)據
// String[] data1 = {"jack","123456","男","25"};
// String[] data2 = {"tom","456789","女","20"};
// String[] data3 = {"mark","aaa","哈哈","21"};
//插入數(shù)據
// 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"));
}
}
數(shù)據庫的配置文件 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
更多關于java相關內容感興趣的讀者可查看本站專題:《Java+MySQL數(shù)據庫程序設計總結》、《Java數(shù)據結構與算法教程》、《Java文件與目錄操作技巧匯總》、《Java操作DOM節(jié)點技巧總結》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
- MySQL創(chuàng)建數(shù)據庫和創(chuàng)建數(shù)據表的操作過程
- mysql如何創(chuàng)建數(shù)據庫并指定字符集
- MongoDB連接和創(chuàng)建數(shù)據庫的方法講解
- DataGrip連接Mysql并創(chuàng)建數(shù)據庫的方法實現(xiàn)
- MySQL創(chuàng)建數(shù)據表并建立主外鍵關系詳解
- 在Mysql上創(chuàng)建數(shù)據表實例代碼
- sqlserver2005自動創(chuàng)建數(shù)據表和自動添加某個字段索引
- MySQL創(chuàng)建數(shù)據庫和創(chuàng)建數(shù)據表
相關文章
Java入門絆腳石之Override和Overload的區(qū)別詳解
重寫是子類對父類的允許訪問的方法的實現(xiàn)過程進行重新編寫, 返回值和形參都不能改變。即外殼不變,核心重寫!重寫的好處在于子類可以根據需要,定義特定于自己的行為。重載是在一個類里面,方法名字相同,而參數(shù)不同。返回類型可以相同也可以不同2021-10-10
一文搞懂Spring中@Autowired和@Resource的區(qū)別
@Autowired?和?@Resource?都是?Spring/Spring?Boot?項目中,用來進行依賴注入的注解。它們都提供了將依賴對象注入到當前對象的功能,但二者卻有眾多不同,并且這也是常見的面試題之一,所以我們今天就來盤它2022-08-08
SpringBoot Mybatis批量插入Oracle數(shù)據庫數(shù)據
這篇文章主要介紹了SpringBoot Mybatis批量插入Oracle數(shù)據庫數(shù)據,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08

