この記事の例では、Java が JDBC を使用してデータ テーブルと SQL 前処理を動的に作成する方法を説明します。参考までに皆さんと共有してください。詳細は次のとおりです:
過去 2 日間の会社のニーズにより、お客様はデータ テーブルのフィールドをカスタマイズする必要がありました。その結果、各テーブルのフィールドはカスタマイズされませんでした。固定されており、汎用テンプレートを維持するのが難しいため、JDBC を使用してデータ テーブルを動的に作成し、データは主にユーザーが提供する Excel を使用してテーブルのフィールドを介して追加されます。これはデータベースに直接インポートされます。
フィールド タイプを考慮すると、リフレクション メカニズムを通じて取得できます。現在、ユーザーの主な要求は、変更できないクエリ関数を提供するためにデータをデータベースにインポートすることです。そのため、文字列を直接使用する方が便利です。データを処理するタイプ。
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")); } }
データベース構成ファイル 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 が JDBC を使用してデータテーブルと SQL 前処理を動的に作成する方法の例の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

jvm'sperformanceiscompetitivewitherruntimes、sped、safety、andproductivityの提供

javaachievesplatformedentenceTheThejavavirtualMachine(JVM)、avainwithcodetorunonanyplatformwithajvm.1)codescompiledintobytecode、notmachine-specificcode.2)

thejvmisanabstractcomputingMachineCrucialForrunningJavaProgramsDuetoitsPlatForm-IndopentInterChitecture.Itincludes:1)ClassLoaderForloadingClasses、2)Runtimedataareaforforforatastorage、3)executionEngineWithinterter、Jitcompiler、およびGarbagecolfecolfecolfececolfecolfer

jvmhasacloserelationshiptheosasittrantesjavabytecodecodecodecodecodecodecodecodecodecodecodecodecodetructions、manageSmemory、およびhandlesgarbagecollection.thisrelationshipallowsjavatorunonvariousosenvirnments、Butalsedentsはspeedifediferentjvmbeviorhiorsandosendisfredediferentjvmbehbehioorysando

Javaの実装「Write and、Run Everywherewhere」はBytecodeにコンパイルされ、Java仮想マシン(JVM)で実行されます。 1)Javaコードを書き、それをByteCodeにコンパイルします。 2)JVMがインストールされたプラットフォームでByteCodeが実行されます。 3)Javaネイティブインターフェイス(JNI)を使用して、プラットフォーム固有の機能を処理します。 JVMの一貫性やプラットフォーム固有のライブラリの使用などの課題にもかかわらず、Woraは開発効率と展開の柔軟性を大幅に向上させます。

javaachievesplatformentenceTheTheTheJavavirtualMachine(JVM)、CodetorunondifferentoperatingSystemswithOutModification.thejvmcompilesjavacodeplatform-IndopentedbyTecodeを承認することを許可します

javaispowerfulfulduetoitsplatformindepentence、object-orientednature、richstandardlibrary、performancecapability、andstrongsecurityfeatures.1)platformendependenceallowseplicationStorunonaydevicesupportingjava.2)オブジェクト指向のプログラマン型

上位のJava関数には、次のものが含まれます。1)オブジェクト指向プログラミング、サポートポリ型、コードの柔軟性と保守性の向上。 2)例外処理メカニズム、トライキャッチ式ブロックによるコードの堅牢性の向上。 3)ゴミ収集、メモリ管理の簡素化。 4)ジェネリック、タイプの安全性の向上。 5)コードをより簡潔で表現力豊かにするためのAMBDAの表現と機能的なプログラミング。 6)最適化されたデータ構造とアルゴリズムを提供するリッチ標準ライブラリ。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

Safe Exam Browser
Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

SublimeText3 中国語版
中国語版、とても使いやすい

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、
