将SELECT c#Cassandra的结果写入CSV文件

时间:2017-05-22 14:44:05

标签: c# cassandra

我想将Cassandra中SELECT查询的结果写入CSV文件。请帮忙。我刚接触C#。这就是我做的。有什么帮助将结果写入CSV文件?感谢

Cluster cluster = Cluster.Builder().AddContactPoint("127.0.0.1").Build();
List<string> lstOfKeyspaces = cluster.Metadata.GetKeyspaces().ToList<string>();
ISession session = cluster.Connect("test");
//get tables in the keysapce
List<string> lstString = cluster.Metadata.GetTables("test").ToList<string>();
Console.WriteLine("Connection succeeded");
//   Console.ReadLine();
//  RowSet resultRequest = session.Execute(" select  * from integrationobjects.emp");
//Execute a query on a connection synchronously
var rs = session.Execute("SELECT * FROM emp");

1 个答案:

答案 0 :(得分:1)

这是解决方案

List<string> lstColumnName = new List<string>();
                string strPath = System.IO.Directory.GetCurrentDirectory();
                try
                {
                    Cluster cassandraCluster = Cluster.Builder().AddContactPoint(strIpAddress).Build();
                    ISession session = cassandraCluster.Connect(strKeyspace);
                    string strCqlRequest = "SELECT * FROM" + " " + strTable;
                    RowSet rs = session.Execute(strCqlRequest);


                    using (var w = new StreamWriter(strPathToSave))
                    {

                        //get table columns with types 
                        TableMetadata t = cassandraCluster.Metadata.GetTable(strKeyspace,strTable);
                        TableColumn[] arrcol = t.TableColumns;

                        foreach (var strCol in arrcol)
                        {
                            lstColumnName.Add(strCol.Name);

                        }
                        IDictionary<string,TableColumn> dic =t.ColumnsByName;

                        //Add column liste to the file
                        var strColumnLine = String.Join(",", lstColumnName.ToArray());
                        w.WriteLine(strColumnLine);
                        //Iterate through the RowSet and add rows to the file
                        foreach (Row row in rs)
                        {
                            List<string> values = new List<string>();
                            IEnumerator<Object> colEnumerator = row.GetEnumerator();

                            while (colEnumerator.MoveNext())
                            {
                                values.Add(colEnumerator.Current.ToString());
                            }
                            var line = String.Join(",", values.ToArray());
                            w.WriteLine(line);
                            w.Flush();

                        }

                    }