4

我正在开发一个项目,其中我在具有不同模式的不同数据库中拥有三个表。所以这意味着我为这三个表使用 JDBC 连接了三个不同的连接参数-

让我们假设——

对于表 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 插入所有三个表或其中任何一个表。

以下是我拥有的三个用例-

  1. 如果假设我只传递 Table1 从命令提示符,那么我假设通过连接到 Table1 仅在 Table1 列中插入。
  2. 如果我从命令提示符传递 Table1、Table2,那么我想通过连接到 Table1 和 Table2 来插入 Table1 和 Table2 列。
  3. 如果我传递 Table1、Table2 和 Table3,那么我假设使用各自的连接参数输入所有三个表

我无法理解如何以更简洁的方式为上述特定场景编写代码,以便如果我想出四个表,它也可以在不久的将来扩展。我可以有一个常量文件,它可以存储需要为三个表中的任何一个执行的 SQL 以及其他一些常量。

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 回答