Maher HTB
Maher HTB

Reputation: 737

Write result of SELECT c# Cassandra into CSV file

I would like to write the result of a SELECT query in Cassandra into a CSV file. Any help, please. I am just new to C#. Here is what I did. Any help to write the result into CSV file? Thanks

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");

Upvotes: 0

Views: 202

Answers (1)

Maher HTB
Maher HTB

Reputation: 737

Here is the solution

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();

                        }

                    }

Upvotes: 1

Related Questions