[英]How to read from mysql and write column wise in csv file?
I have different tables in a database(say mysql). 我在数据库中有不同的表(例如mysql)。 i need to extract some columns from different table and write it in a csv file.
我需要从不同的表中提取一些列,并将其写入csv文件中。 consider table 1
考虑表1
A 1
B 2
C 3
table 2 table 3
X 7 AB A1
Y 8 BC B2
Z 10 CD C3
U 11 DE D4
V 12
W 13
i want to write 1st column from table 1,2nd col from table 2, and 1st col from table 3 in a csv file such that empty rows are made null. 我想在csv文件中将表1,2的第1列,表2的第1列和表3的第1列写入CSV文件中,以使空行成为null。
output:
A,7,AB
B,8.BC
C,10,CD
null,11,DE
null,12,null
null,13,null
i can do the basic reading and writing from mysql to csv, need help in the logic or code to get the above output. 我可以进行从mysql到csv的基本读写,需要逻辑或代码方面的帮助才能获得上述输出。 "Looking for a generic solution for say 'n' number of columns from 'n' number of tables".
“正在寻找一种通用解决方案,以从'n'个表中得出'n'个列”。 above is jus a example.
以上是一个例子。
Since you just want the logic here is some pseudo code that may help you in whatever language you are using. 由于您只想了解逻辑,因此这里提供了一些伪代码,它们可能会以您使用的任何语言为您提供帮助。 Since I don't know how you are exporting to csv I made it pretty generic.
由于我不知道您是如何导出到csv的,因此使它变得非常通用。
arr1 = select column1 from table1;
arr2 = select column2 from table2;
arr3 = select column1 from table3;
max = isBigger(arr1.length, arr2.length);
max = isBigger(max, arr3.length);
for(i=0; i<max; i++)
{
if(arr1[i]=="") arr1[i]=null;
if(arr2[i]=="") arr2[i]=null;
if(arr3[i]=="") arr3[i]=null;
print arr1[i] + "," + arr2[i] + "," + arr3[i];
}
I do not know how you read your database but assume you do it with JDBC: 我不知道您如何读取数据库,但假设您是使用JDBC进行的:
ResultSet tableAReusltSet= null;
ResultSet tableBReusltSet= null;
ResultSet tableCReusltSet= null;
List<PseudeContainer> container = new ArrayList<>();
while (tableAReusltSet.next()) {
PseudeConteiner ps = new PseudoContainer();
ps.col1 = tableAReusltSet.getString("ColumnName");
container.add(ps);
}
int i = 0;
while (tableBReusltSet.next()) {
if(container.size() <= i){
container.add(new PseudeContainer());
}
container.get(i).col2 = tableBReusltSet.getString("ColumnName");
}
i = 0;
while (tableBReusltSet.next()) {
if(container.size() <= i){
container.add(new PseudeContainer());
}
container.get(i).col2 = tableBReusltSet.getString("ColumnName");
}
//.. now you have a collection to work with which you can write // ..现在您可以使用一个集合来编写
public PseudeContainer {
String col1 = null;
String col2 = null;
String col3 = null;
}
Above should work.. still pseudo code... 上面应该工作..仍然是伪代码...
Recommend 3rd party libraries to handle CSV files: 推荐第三方库处理CSV文件:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.