我正在开发一个项目,其中不同的数据库中有三个具有不同模式的表。这意味着我有三个不同的连接参数来使用 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 插入所有三个表或其中任何一个表。
以下是我的三个用例 -
- 在命令提示符下,如果假设我仅传递 Table1,那么我应该通过连接到仅在 Table1 列中插入
表格1。
- 如果我从命令提示符传递 Table1、Table2,那么我应该通过以下方式插入 Table1 和 Table2 列:
连接到表 1 和表 2。
- 如果我传递 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;
}
谁能对此提供一些想法,我应该如何继续?
Note:-
每个表中的列会有很大差异。就像在某些表中,列可以是 10,而在其他一些表中,列可以是 20。
Create 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
file.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)