4

私は、異なるスキーマを持つ異なるデータベースに 3 つのテーブルがあるプロジェクトに取り組んでいます。つまり、JDBC を使用して接続するために、これら 3 つのテーブルに対して 3 つの異なる接続パラメーターがあることを意味します。

仮定しましょう-

表1の場合-

Username:- A
Password:- B
URL:       C

Columns-
ID1         String
Account1    String

表2の場合-

Username:- P
Password:- Q
URL:-      R

Columns-
ID2         String
Account2    String

表3の場合-

Username:- T
Password:- U
URL:-      V

Columns-
ID3         String
Account3    String

そして、JDBC を使用して 3 つのテーブルすべて、またはいずれか 1 つに挿入することになっています。

以下は、私が持っている3つのユースケースです-

  1. コマンド プロンプトから、Table1 のみを渡していると仮定すると、Table1 に接続して Table1 列にのみ挿入すると仮定します。
  2. また、コマンド プロンプトから Table1、Table2 を渡す場合、Table1 と Table2 に接続して、Table1 と Table2 の両方の列に挿入することを想定しています。
  3. そして、Table1、Table2、および Table3 を渡す場合、それぞれの接続パラメーターを使用して 3 つのテーブルすべてに入力することを想定しています。

上記の特定のシナリオのコードをそのようなクリーンな方法で記述する方法を理解できないため、近い将来、4 つのテーブルを作成した場合にも拡張できます。3 つのテーブルのいずれかに対して実行する必要がある SQL を格納できる 1 つの定数ファイルと、その他の定数ファイルを作成することもできます。

public static void main(String[] args) {


}


 class Task implements Runnable {

    private Connection dbConnection = null;
    private PreparedStatement preparedStatement = null;

    public Task() {

    }

    @Override
    public void run() {

    dbConnection = getDbConnection();

    //prepare the statement and execute it

    }
  }


    private Connection getDBConnection() {

    Connection dbConnection = null;

          Class.forName(Constants.DRIVER_NAME);
      dbConnection = DriverManager.getConnection( , , );

      return dbConnection;
    }

これについて誰かが考えを提供できますか?

ノート:-

各テーブルの列は大きく異なります。一部のテーブルのように、列は 10 になり、他のテーブルでは列は 20 になります。

4

2 に答える 2

3

databases.properties次のような内容のファイルを作成します。

# Table 1
table1.url: jdbc:mysql://localhost:3306/garden
table1.user: gardener
table1.password: shavel
table1.table: fruits
table1.column.id: fruitID
table1.column.color: fruitColor
table1.column.weight: fruitWeight
# ... More fruit columns here ...

# Table 2
table2.url: jdbc:mysql://otherhost:3306/forest
table2.user: forester
table2.password: axe
table2.table: trees
table2.column.id: treeID
table2.column.height: treeHeight
# ... More tree columns here ...

# ... More tables here ...

次に、次のようにします。

public static void main (String [] args)
{
    Properties databasesProperties = new Properties ();
    databasesProperties.load ("databases.properties");

    for (String arg: args)
    {
        String url = databasesProperties.get (arg + ".url");
        String user = databasesProperties.get (arg + ".user");
        String password= databasesProperties.get (arg + ".password");
        String table = databasesProperties.get (arg + ".table");

        String columnPrefix = arg + ".column."
        Map <String, String> columns = new HashMap <String, String> ();
        for (String key: databasesProperties.stringPropertyNames ())
        {
            if (key.startsWith (columnPrefix))
                columns.put (
                    key.substring (columnPrefix.length ()), 
                    databasesProperties.get (key));
        }

        doInsert (url, user, password, table, columns);
    }
}

後でいつでもテーブルをファイルに追加できdatabases.propertiesます。

于 2013-02-09T08:24:12.450 に答える
0

データベース プロパティをクラス ファイルに保存しますDBPropery.java

final class DBProperty
{
    static String[]  urls = {
                        "C",
                        "R",
                        "V"
                    }; //You can add more URLs here.
    static String[] driver= {
                        "Driver1",
                        "Driver2",
                        "Driver3"
                    };//You can add more drivers string
    static String[]  table = {
                        "Table1",
                        "Table2",
                        "Table3"
                    };//You can add more table names here According to URLs mentioned in urls array.
    static String[]  user = {
                        "A",
                        "P",
                        "T"
                    };//You can add more user names here according to URls mentioned in urls array.
    static String[]  pwd = {
                        "B",
                        "Q",
                        "U"
                    };//You can add more Password here according to URls mentioned in urls array.
    static String[] queries = {
                        "Query for Table1",
                        "Query for Table2",
                        "Query for Table3",
                    };//You can add more queries here for more tables according to URls mentioned in urls array.
    static int[]  columns ={
                        2,
                        2,
                        2
                    };//You can change the column numbers according to need . 0th index belongs to Table1 , 1 to table2....so on. 
                      //If you add more tables , add corresponding columns count to next index.
    static String[] columnValues ={
                                "1^John",
                                "34^Vicky",
                                "65^Ethen"
                            };//String at each index represents a row in corresponding table in table[] array. each column is seperated by delimiter "^".
}

ファイル内のすべての変更を行いDBProperty.javaます。
次に、次のクラスファイルに進みます

import java.sql.*;
import java.util.*;
class MultiTableInsert implements Runnable
{
    Map<String,Integer> columnsInTable;
    Map<String,String>  tableDriver;
    Map<String,String>  rowForTable;
    Map<String,String>  queryForTable;
    Map<String,String>  urlForTable;
    Map<String,String>  userForTable;
    Map<String,String>  pwdForTable;
    String[]                tables ;
    public MultiTableInsert(String... tables)//Loading all Database Settings here..
    {
        this.tables = tables;
        columnsInTable  = new LinkedHashMap<String,Integer>();
        rowForTable = new LinkedHashMap<String,String>();
        tableDriver = new LinkedHashMap<String,String>();
        urlForTable = new LinkedHashMap<String,String>();
        userForTable= new LinkedHashMap<String,String>();
        pwdForTable = new LinkedHashMap<String,String>(); 
        for (int i = 0 ; i < DBProperty.urls.length ; i++ )
        {
            try
            {
                tableDriver.put(DBProperty.table[i],DBProperty.driver[i]);
                queryForTable.put(DBProperty.table[i],DBProperty.queries[i]);
                columnsInTable.put(DBProperty.table[i],DBProperty.columns[i]);
                rowForTable.put(DBProperty.table[i],DBProperty.columnValues[i]);
                urlForTable.put(DBProperty.table[i],DBProperty.urls[i]);
                userForTable.put(DBProperty.table[i],DBProperty.user[i]);
                pwdForTable.put(DBProperty.table[i],DBProperty.pwd[i]);
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
    @Override
    public void run()
    {
        insertIntoTable(tables);
    }
    private void insertIntoTable(String... tables)
    {
        for (String tble : tables )
        {
            Connection con = null;
            PreparedStatement pStmt = null;
            try
            {
                Class.forName(tableDriver.get(tble));
                con = DriverManager.getConnection(urlForTable.get(tble),userForTable.get(tble),pwdForTable.get(tble)); 
                pStmt = con.prepareStatement(queryForTable.get(tble));
                int columns = columnsInTable.get(tble);
                String sRow = rowForTable.get(tble);
                StringTokenizer tokenizer = new StringTokenizer(sRow,"^");
                for (int i = 0; i < columns ; i++)
                {
                    pStmt.setString(i+1,(String)tokenizer.nextElement());
                }
                pStmt.execute();
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
            finally
            {
                try
                {
                    con.close();
                }catch (Exception ex){}
                try
                {
                    pStmt.close();
                }catch (Exception ex){}
            }
        }
    }
    public static void main(String[] args) 
    {
        int length = args.length;
        int THREAD_COUNTS = 10;//Number of threads you want to start.
        switch (length)
        {
            case 0: 
                    System.out.println("Usage: javac MultiTableInsert Table1/Table2/Table3 <Table1/Table2/Table3> <Table1/Table2/Table3>");
                    System.exit(0);
            case 1:
                    for (int i = 0 ; i < THREAD_COUNTS ; i++)
                    {
                        MultiTableInsert mti = new MultiTableInsert(args[0]);
                        Thread th = new Thread(mti,"Thread"+i);//Create New Thread
                        th.start();                             //Start Thread
                    }
                    break;
            case 2:
                    for (int i = 0 ; i < THREAD_COUNTS ; i++)
                    {
                        MultiTableInsert mti = new MultiTableInsert(args[0],args[1]);//Create New Thread 
                        Thread th = new Thread(mti,"Thread"+i);                      //Start Thread     
                        th.start();
                    }
                    break;
            default:
                    for (int i = 0 ; i < THREAD_COUNTS ; i++)
                    {
                        MultiTableInsert mti = new MultiTableInsert(args[0],args[1],args[2]);//Create New Thread 
                        Thread th = new Thread(mti,"Thread"+i);                              //Start Thread     
                        th.start();
                    }
                    break;
        }
    }
}
于 2013-02-09T14:04:14.183 に答える