how insert data array to database with linq to sql?
DataClassesDataContext db = new DataClassesDataContext();
simpleTbl tbl = new simpleTbl();
string[] str =File.ReadAllLines(Server.MapPath("~/str.txt"));
for (int i = 0; i <= 10; i++)
{
tbl.Name =str[i];
}
db.simpleTbl.InsertOnSubmit(tbl);
db.SubmitChanges();
but dosent work
using(DataClassesDataContext db = new DataClassesDataContext())
{
string[] strings = File.ReadAllLines(Server.MapPath("~/str.txt"));
foreach (var str in strings )
{
db.simpleTbl.InsertOnSubmit(new simpleTbl(){ Name = str });
}
db.SubmitChanges();
}
You need to insert a new item for each entry in the string array.
this code is correct but uses for one array if i have more one array how implement this?
using(DataClassesDataContext db = new DataClassesDataContext())
{
string[] strings = File.ReadAllLines(Server.MapPath("~/str.txt"));
foreach (var str in strings )
{
db.simpleTbl.InsertOnSubmit(new simpleTbl(){ Name = str });
}
db.SubmitChanges();
}
Related
How can I print all the column names?
Console.WriteLine(row.RawRow.ETag); does not work it prints blank lines
This is my code so far
static void Main(string[] args)
{
List<string> rows = new List<string>();
string projectId = "project-id 123";
var client = BigQueryClient.Create(projectId);
string sql = #"SELECT * FROM table";
var res = client.ExecuteQuery(sql, parameters: null);
foreach (var row in res)
Console.WriteLine(row["id"])
//rows.Add(row["id"])
}
One of the examples has your answer
Here
public List<T> Execute<T>(string sql)
{
var client = BigQueryClient.Create(projectId);
List<T> result = new List<T>();
try
{
string query = sql;
BigQueryResults results = client.ExecuteQuery(query, parameters: null);
List<string> fields = new List<string>();
foreach (var col in results.Schema.Fields)
{
fields.Add(col.Name);
}
i have to import 2 CSV's.
CSV 1 [49]: Including about 50 tab seperated colums.
CSV 2:[2] Inlcudes 3 Columns which should be replaced on the [3] [6] and [11] place of my first csv.
So heres what i do:
1) Importing the csv and split into a array.
string employeedatabase = "MYPATH";
List<String> status = new List<String>();
StreamReader file2 = new System.IO.StreamReader(filename);
string line = file2.ReadLine();
while ((line = file2.ReadLine()) != null)
{
string[] ud = line.Split('\t');
status.Add(ud[0]);
}
String[] ud_status = status.ToArray();
PROBLEM 1: i have about 50 colums to handle, ud_status is just the first, so do i need 50 Lists and 50 String arrays?
2) Importing the second csv and split into a array.
List<String> vorname = new List<String>();
List<String> nachname = new List<String>();
List<String> username = new List<String>();
StreamReader file = new System.IO.StreamReader(employeedatabase);
string line3 = file.ReadLine();
while ((line3 = file.ReadLine()) != null)
{
string[] data = line3.Split(';');
vorname.Add(data[0]);
nachname.Add(data[1]);
username.Add(data[2]);
}
String[] db_vorname = vorname.ToArray();
String[] db_nachname = nachname.ToArray();
String[] db_username = username.ToArray();
PROBLEM 2: After loading these two csv's i dont know how to combine them, and change to columns as mentioned above ..
somethine like this?
mynewArray = ud_status + "/t" + ud_xy[..n] + "/t" + changed_colum + ud_xy[..n];
save "mynewarray" into tablulator seperated csv with encoding "utf-8".
To read the file into a meaningful format, you should set up a class that defines the format of your CSV:
public class CsvRow
{
public string vorname { get; set; }
public string nachname { get; set; }
public string username { get; set; }
public CsvRow (string[] data)
{
vorname = data[0];
nachname = data[1];
username = data[2];
}
}
Then populate a list of this:
List<CsvRow> rows = new List<CsvRow>();
StreamReader file = new System.IO.StreamReader(employeedatabase);
string line3 = file.ReadLine();
while ((line3 = file.ReadLine()) != null)
{
rows.Add(new CsvRow(line3.Split(';'));
}
Similarly format your other CSV and include unused properties for the new fields. Once you have loaded both, you can populate the new properties from this list in a loop, matching the records by whatever common field the CSVs hopefully share. Then finally output the resulting data to a new CSV file.
Your solution is not to use string arrays to do this. That will just drive you crazy. It's better to use the System.Data.DataTable object.
I didn't get a chance to test the LINQ lambda expression at the end of this (or really any of it, I wrote this on a break), but it should get you on the right track.
using (var ds = new System.Data.DataSet("My Data"))
{
ds.Tables.Add("File0");
ds.Tables.Add("File1");
string[] line;
using (var reader = new System.IO.StreamReader("FirstFile"))
{
//first we get columns for table 0
foreach (string s in reader.ReadLine().Split('\t'))
ds.Tables["File0"].Columns.Add(s);
while ((line = reader.ReadLine().Split('\t')) != null)
{
//and now the rest of the data.
var r = ds.Tables["File0"].NewRow();
for (int i = 0; i <= line.Length; i++)
{
r[i] = line[i];
}
ds.Tables["File0"].Rows.Add(r);
}
}
//we could probably do these in a loop or a second method,
//but you may want subtle differences, so for now we just do it the same way
//for file1
using (var reader2 = new System.IO.StreamReader("SecondFile"))
{
foreach (string s in reader2.ReadLine().Split('\t'))
ds.Tables["File1"].Columns.Add(s);
while ((line = reader2.ReadLine().Split('\t')) != null)
{
//and now the rest of the data.
var r = ds.Tables["File1"].NewRow();
for (int i = 0; i <= line.Length; i++)
{
r[i] = line[i];
}
ds.Tables["File1"].Rows.Add(r);
}
}
//you now have these in functioning datatables. Because we named columns,
//you can call them by name specifically, or by index, to replace in the first datatable.
string[] columnsToReplace = new string[] { "firstColumnName", "SecondColumnName", "ThirdColumnName" };
for(int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//you didn't give a sign of any relation between the two tables
//so this is just by row, and assumes the row count is equivalent.
//This is also not advised.
//if there is a key these sets of data share
//you should join on them instead.
foreach(DataRow dr in ds.Tables[0].Rows[i].ItemArray)
{
dr[3] = ds.Tables[1].Rows[i][columnsToReplace[0]];
dr[6] = ds.Tables[1].Rows[i][columnsToReplace[1]];
dr[11] = ds.Tables[1].Rows[i][columnsToReplace[2]];
}
}
//ds.Tables[0] now has the output you want.
string output = String.Empty;
foreach (var s in ds.Tables[0].Columns)
output = String.Concat(output, s ,"\t");
output = String.Concat(output, Environment.NewLine); // columns ready, now the rows.
foreach (DataRow r in ds.Tables[0].Rows)
output = string.Concat(output, r.ItemArray.SelectMany(t => (t.ToString() + "\t")), Environment.NewLine);
if(System.IO.File.Exists("MYPATH"))
using (System.IO.StreamWriter file = new System.IO.StreamWriter("MYPATH")) //or a variable instead of string literal
{
file.Write(output);
}
}
With Cinchoo ETL - an open source file helper library, you can do the merge of CSV files as below. Assumed the 2 CSV file contains same number of lines.
string CSV1 = #"Id Name City
1 Tom New York
2 Mark FairFax";
string CSV2 = #"Id City
1 Las Vegas
2 Dallas";
dynamic rec1 = null;
dynamic rec2 = null;
StringBuilder csv3 = new StringBuilder();
using (var csvOut = new ChoCSVWriter(new StringWriter(csv3))
.WithFirstLineHeader()
.WithDelimiter("\t")
)
{
using (var csv1 = new ChoCSVReader(new StringReader(CSV1))
.WithFirstLineHeader()
.WithDelimiter("\t")
)
{
using (var csv2 = new ChoCSVReader(new StringReader(CSV2))
.WithFirstLineHeader()
.WithDelimiter("\t")
)
{
while ((rec1 = csv1.Read()) != null && (rec2 = csv2.Read()) != null)
{
rec1.City = rec2.City;
csvOut.Write(rec1);
}
}
}
}
Console.WriteLine(csv3.ToString());
Hope it helps.
Disclaimer: I'm the author of this library.
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");
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();
}
}
I have an array that consist of First Name _ Last Name so they would read like so
Michael_Jordan
Javier_Lopez
George_Jones
I have an loop set-up to iterate through each of these, but I only want to take what's after the "" The problem I have is that the array was declared globally, and it is declared in far to many places for me to change. If I try to use the .Split function I receive an error of System.Array does not contain a definition for split. What is another option to take the data after the "" in the array?
public static string GetEmployees()
{
string queryString = "select employeeName from tbl_GlobalEmployeeData where state = 'AL';
SqlConnection connection = new SqlConnection(Connection.MyConnectionString.ConnectionStrings[0]);
{
SqlCommand cmd = new SqlCommand(queryString, connection);
connection.Open();
List<string> tempList = new List<string>();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
try
{
if (!reader.IsDBNull(0))
{
tempList.Add(reader[0].ToString() + "_" + reader[1].ToString());
}
}
catch
{
if (!reader.IsDBNull(0))
{
tempList.Add(reader[0].ToString() + "_" + reader[1].ToString());
}
}
}
reader.Close();
AllCompanyEmployees.State.ThisStore = tempList.ToArray();
for (int q = AllCompanyEmployees.State.ThisStore.GetLowerBound(0); q <= AllCompanyEmployees.State.ThisStore.GetUpperBound(0); q++)
{
return AllCompanyEmployees.State.ThisStore[q];
}
return null;
}
}
}
for (int q = AllCompanyEmployees.State.ThisStore.GetLowerBound(0); q <= AllCompanyEmployees.State.ThisStore.GetUpperBound(0); q++)
{
//This line is where I get the error mentioned above
string lastName = AllCompanyEmployees.State.ThisStore.Split('_')[1];
}
I think your question is "I want to split the array - So for example it reads Javier_Lopez I want to take Lopez from the array"
Very easy:
string last = yourString.Split(new char[] { '_' })[1];
Again, you seem to be using this on an array which is why you are getting that error. You need to iterate through your array and do this on each individual string in your array.
EDIT: To modify the array and leave only last names, try this:
int i = 0;
foreach (string s in stringArray)
{
stringArray[i] = stringArray[i].Split(new char[] { '_' })[1];
i++;
}
You can only use Split on strings. So you could do something like this:
List<string> lastNames = new List<string>();
for (int q = AllCompanyEmployees.State.ThisStore.GetLowerBound(0); q <= AllCompanyEmployees.State.ThisStore.GetUpperBound(0); q++)
{
string lastName = AllCompanyEmployees.State.ThisStore[q].Split('_')[1];
lastNames.Add(lastName);
}
At the end you would have a List<string> with all last names of your employees. With that you can continue to work.
I'm using this code to parse the values and store them in List. The first row has names which are getting stored fine. But when storing values, only the second row is bring saved. I'm not sure what edit I need to make so that it parses all other rows as well.
Please see image and code below.
List<string> names = new List<string>(); // List to store Key names
List<string> values = new List<string>(); // List to store key values
using (StreamReader stream = new StreamReader(filePath))
{
names = stream.ReadLine().Split(',').ToList(); // Seperate key names and store them in a List
values = stream.ReadLine().Split(',').ToList(); // Seperate key values and store them in a list
}
See if something like this works better:
// List to store Key names
List<string> names = new List<string>();
// List to store key values
List<List<string>> values = new List<string>();
using (StreamReader stream = new StreamReader(filePath))
{
if(!stream.EndOfStream)
{
// Seperate key names and store them in a List
names = stream.ReadLine().Split(',').ToList();
}
while(!stream.EndOfStream)
{
// Seperate key values and store them in a list
values.Add(stream.ReadLine().Split(',').ToList());
}
}
This changes your values list to be a list of a list of strings so that each row will a list of string
While this probably isn't the best way to parse a .csv, if your data is consistent and the file format is strongly consistent you can probably get away with doing it like this. As soon as you try this with odd values, quoted strings, strings with commas, etc., you'll need a different approach.
i have written the code for grid view make changes it to a list.I think it will help
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string s = FileUpload1.FileName.Trim();
if (s.EndsWith(".csv"))
{
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/data/" + s));
string[] readText = File.ReadAllLines(Server.MapPath("~/data/" + s));
DataSet ds = new DataSet();
DataTable dt = new DataTable();
// Array.Sort(readText);
for (int i = 0; i < readText.Length; i++)
{
if (i == 0)
{
string str = readText[0];
string[] header = str.Split(',');
dt.TableName = "sal";
foreach (string k in header)
{
dt.Columns.Add(k);
}
}
else
{
DataRow dr = dt.NewRow();
string str1 = readText[i];
if (readText[i] == ",,,,")
{
break;
}
string[] rows = str1.Split(',');
if (dt.Columns.Count == rows.Length)
{
for (int z = 0; z < rows.Length; z++)
{
if (rows[z] == "")
{
rows[z] = null;
}
dr[z] = rows[z];
}
dt.Rows.Add(dr);
}
else
{
Label1.Text = "please select valid format";
}
}
}
//Iterate through the columns of the datatable to set the data bound field dynamically.
ds.Merge(dt);
Session["tasktable"] = dt;
foreach (DataColumn col in dt.Columns)
{
BoundField bf = new BoundField();
bf.DataField = col.ToString();
bf.HeaderText = col.ColumnName;
if (col.ToString() == "Task")
{
bf.SortExpression = col.ToString();
}
GridView1.Columns.Add(bf);
}
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
Label1.Text = "please select a only csv format";
}
}
else
{
Label1.Text = "please select a file";
}
}