Good morning,
I´m trying to create a program to create statements in a .Sql document but i´m having some troubles.
this is my code so far:
string[] filas = File.ReadAllLines("c:\\temp\\Statements.txt");
StreamWriter sw = new StreamWriter("c:\\temp\\Statements.sql");
foreach (string fila in filas)
{
string sql = "INSERT ";
string[] campos = fila.Split(' ');
if (campos[0]== "1A")
{
sql += " INTO TABLE1 (field1) VALUES (" + campos[1] + ");";
}
else
{
sql += " INTO TABLE2 (field1,field2,field3) VALUES (" + campos[1] + "," + campos[2] + "," + campos[3] + ");";
}
sw.WriteLine(sql);
}
sw.Close();
{
the thing is:
I need to read a txt document (the lenght will change), and then transform it to a sql document with all the statements, there are only two tipes of lines starting in "1A" or "2B", example:
1A123456 456,67
2B123456 mr awesome great strt germany
1A123456 456,67
2B123456 mr awesome great strt germany
2B123456 mr awesome great strt germany
1A123456 456,67
1A123456 456,67
then im trying to "transform" that information on "inserts":
INSERT INTO TABLE1 (REF,MONEY) VALUES (A123456,456,67);
INSERT INTO TABLE2 (REF,NAME,ADR) VALUES (B123456,mr awesome,great strt);
INSERT INTO TABLE1 (REF,MONEY) VALUES (A123456,456,67);
INSERT INTO TABLE2 (REF,NAME,ADR) VALUES (B123456,mr awesome,great strt);
INSERT INTO TABLE2 (REF,NAME,ADR) VALUES (B123456,mr awesome,great strt);
INSERT INTO TABLE1 (REF,MONEY) VALUES (A123456,456,67);
INSERT INTO TABLE1 (REF,MONEY) VALUES (A123456,456,67);
my code is not working so well... i hope someone can help me a litte :).
regards.
Firstly I could not see space between 1A and 123456 . So if (campos[0]== "1A") will not work. Use contains method to do this check - if (campos[0].contains("1A"). you can alternately evaluate using startswith
Secondly you need to split 1A123456 to get A123456 .. you can use substring or similar functions for same. (Same for 2B)
Thirdly, you are splitting the string with ' ' - this could result in many more string than your anticipated strings. 2B123456 mr awesome great strt germany - in this case mr awesome great strt are all different. You need to put in logic to concatenate campos[1] & campos[2] and campos[3] & campos[1=4] in the case of 2B ....
Fourthly for the 1A case you need to split campos[1] using , as delimiter to get the two values you want
Hope this provides you enough guidance to solve your issue.
After some research and with the help from anil and Pikoh i found a good solution:
string mydate = DateTime.Now.ToString("yyyyMMdd");
string AÑO = DateTime.Now.ToString("yyyy");
string MES = DateTime.Now.ToString("MM");
string DIA = DateTime.Now.ToString("dd");
string sql = "INSERT ";
string[] campos = fila.Split(' ');
if (campos[0].StartsWith("1H"))
{
sql += "INTO TABLE (VALUES,VALUES,VALUES) VALUES (" + "'" + mydate + "'" + "," + "'" + campos[0].Substring(1, 8) + "'" + "," + "'" + campos[0].Substring(9, 7) + "'" + "," + "'" + campos[8] + "'" + ");";
Inserting data and manipulating strings was good, but now i have the last problem,
what happen if i need to make a "backspace" to an specific string because my logic cant pick the correct information? regards.
Related
Okay so I have some c# that generated href anchor tags styled as list items and throws it onto an aspx page like so;
html += "<a href='../InspectionView.aspx' class='list-group-item' id=''>Inspection ID: " + inspectionID + " - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
Now this is in a loop, the variables are pulled from a SQL database and used to populate that html string.
Now, what I'm trying to do is have it so when the user clicks on one of the generated hrefs, and is redirected to the next page, the variable inspectionID is passed forward. I thought there might be someway of storing it in the ID of the href tag but I dont know where to go from there.
Thanks a lot.
Add a query string parameter.
html += "<a href='../InspectionView.aspx?inspectionID='" + inspectionID + " class='list-group-item' id=''>Inspection ID: " + inspectionID + " - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
For reading on the receiving page:
string inspectionID = Request.QueryString["inspectionID"];
See
https://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring(v=vs.110).aspx
a very simple way is to stick into a query string. Since this isn't a server control it might be the only way to it.
something like...
html += "<a href='../InspectionView.aspx?InspectionID="+HttpUtility.UrlEncode(Inspection_ID.ToString())+"&anyotherQSField="+HttpUtility.UrlEncode(anyotherQSFieldVariable) + "' class='list-group-item'> - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
Then in InspectionView.aspx,get values with something like:
String strInspection_ID = Request.QueryString["InspectionID"];
You likely need to convert to string for this to work for the ID.
You dont have to use HttpUtility.UrlEncode for Inspection_ID but if you have other strings you want to use in QS that might contain spaces or other odd characters - it would be wise.
string q="SELECT CONCAT(" + table_users + ".f_name," + table_users + ".l_name) AS Username, (" + table_ship + ".name_it-ITA) AS Lang FROM...";
Hello, I have trouble with this special charachter "-". In PHP I resolve it with backticks, but in C# I cannot resolve it.
Tried with [] and backticks, also with '', but no success.
It would be easier to rename column header name "name_it-ITA", but I cannot do that.
Do you have any idea?
BR
In mysql you can use always bacticks these are not related to C#
"SELECT CONCAT(" + table_users + ".f_name," + table_users + ".l_name) AS Username,
(" + table_ship + ".`name_it-ITA`) AS Lang FROM..."
In mysql all column and table name can wrapped with backtics
I have some vehicle information that I want to send in an email.
I have all code working but spacing out the information is a problem. Each vehicle has a checklist and that checklist then gets emailed. So I loop through the list and get the defect and the comment.
foreach (var item in chkList.CheckItems)
{
if (item.Defect == true)
{
defect += item.ItemTitle + " " + item.Comment + "\n";
}
}
if (hasDefect == true)
{
Utils.ChecklistSendMail("Checklist", ToAddresses.Split(';'),
"Vehicle Reg: " + reg + "\n" +
"Checklist No: " + chkList.CheckListNo + "\n"+
"Date: " + ChecklistDate.ToShortDateString() + "\n" +
"Defects: Comments: " + "\n" +
defect);
}
Email then looks like this:
Vehicle Reg: XLZ 8194
Checklist No: 0
Date: 22/03/2016
Defects: Comments:
Vehicle Secure comment1
Brakes comment2
I want the defects and the comments to be displayed like this:
Defects: Comments:
Vehicle Secure comment1
Brakes comment2
How do I evenly space out the defects and the comments?
You can use string.Format which supports automated padding:
string s = string.Format("{0,-20}{1}", "hello", "world");
Which outputs:
hello world
If you do that for every line, and you find a good distance (20 in my sample code), you will be fine. This all assumes the use of a mono-spaced font.
Use String.Format with the width specifier:
if (item.Defect == true)
{
defect += string.Format("{0,-20} {1,-10}\n", item.ItemTitle, item.Comment);
}
You could also use StringBuilder.AppendFormat if performance becomes an issue.
If you want to guarantee that the columns are aligned, even with a client that uses proportional fonts, then consider rendering as HTML and using a <table> instead.
I have a database table "Leave".
Its primary key is "LeaveNo".
The other fields in the database include "LeaveDate", "EmpID" , "EmpName" , etc
I want to use the dataset.tables["Leave"].Select() method to acquire only the leaves the employee has made in a single month.
The best way I figured was to use two intervals i.e mm/01/2012 and mm/31/2012
(I know some months have 30 days)
My current code is this and it does not work:
This was just a test code...
string moreThan = DateTime.Now.Month.ToString() + "01" + DateTime.Now.Year.ToString();
string lessThan = DateTime.Now.Month.ToString() + "31" + DateTime.Now.Year.ToString();
leavesthisMonth = LeaveDS.Tables["Leave"].Select("EmpID='" + txt_EmpID.Text + "' AND LeaveDate <= '" + "#" + lessThan + "#" + "'" + "AND LeaveDate >= '" + "#" + moreThan + "#" + "'");
Can someone help me with this ???
Working with DataSets and DataTables means that you are not bound (or anyway no more) to a database or specific SQL dialect.
The syntax used with the DataTable.Select() method is documented on MSDN.
For dates (obviously if the column type is REALLY DateTime) is used a syntax similar to MS Access (# delimited), so you can write:
var rows = dt.Select("LeaveDate > #2013-01-01#");
Is important to NOT use quotes (as in #Waqas code):
var rows = dt.Select("LeaveDate > '#2013-01-01#'"); // ERROR
because results in: System.FormatException: String was not recognized as a valid DateTime.
My advice is to use the yyyy-MM-dd format because is culture invariant by design.
A good way to build strings with a specific syntax is to use String.Format (or any variants) for clarity reasons, and let the DateTime type do all the specific date maths.
int month = 10;
var begin = new DateTime(DateTime.Today.Year,month,1); // first day of a month
var end = begin.AddMonths(1); // first day next month
var format = "LeaveDate >= #{0:yyyy-MM-dd}# AND LeaveDate < #{1:yyyy-MM-dd}#";
var condition = String.Format(format,begin,end);
rows = dt.Select(condition);
Notice your operator <= LeaveDate and >= LeaveDate
The operator it should be like >= LeaveDate and <= LeaveDate
The LeaveDate it should be like LeaveDate.ToString("dd MMM yyyy") or LeaveDate.ToString("dd/mm/yyyy")
leavesthisMonth = LeaveDS.Tables["Leave"].Select("EmpID='" + txt_EmpID.Text + "' AND (LeaveDate >= #" + lessThan + "# AND LeaveDate <= #" + moreThan + "#)");
You could make the whole thing a lot easier by using Date() in the SQL:
WHERE Month(LeaveDate)=Month(Date()) AND Year(LeaveDate)=Year(Date())
That removes all the date handling to MS Access and avoids a lot of problem.
I have a table EXPENSES in a mysql database and one of the columns is AMMOUNT with decimal(10,2) as type. I have an application in C# (winforms) with a textbox that is used to insert values in the database.
string initialquery = "INSERT INTO EXPENSES (ID, E_DATE, AMMOUNT, PERSON, COMMENTS, T_ID) " +
"VALUES ('" + id + "', '" + date.ToString("yyyy:MM:dd") + "', '" + ammount + "', '" + person + "', '" + comments + "', '" + tid + "')";
//yyyy:MM:dd hh:mm:ss
myMySqlConnection.Open();
MySqlCommand command1 = new MySqlCommand(initialquery, myMySqlConnection);
command1.ExecuteNonQuery();
if (lang == 2)
MessageBox.Show("ΤΑ ΔΕΔΟΜΕΝΑ ΑΠΟΘΗΚΕΥΤΗΚΑΝ");
else if (lang == 1)
MessageBox.Show("DATA SAVED");
myMySqlConnection.Close();
The problem has to do with the regional settings. If i set the format to GREEK. The decimal symbol is ",". When i try to insert a decimal value with a "," it doesn't accept it (is stored as 405 instead of 40,5). If i set the decimal symbol to"." and i have in the textbox 40.5 is stored correctly. If i set the Regional settings to ENGLISH and i set the decimal value to "," again is not working. Seems like that decimal numbers are accepted only when the decimal symbol is a "." I don't quite understand this. How can i make it accept the "," as a decimal operator?
Best Regards
George Georgiou
I think you set the regional setting of your development machine but SQL Server still in en-us mode, so change the regional setting of your SQL server as well.
Hope it may accept the decimal as you want.
You can use CultureInfo.InvariantCulture when converting from decimal to string.
See msdn
Quoting:
decimal value = -16325.62m;
// Display value using the invariant culture.
Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
// Display value using the en-GB culture.
Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB")));
// Display value using the de-DE culture.
Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE")));
// This example displays the following output to the console:
// -16325.62
// -16325.62
// -16325,62
Note that if your user use commas in his input, you can use the machine culture to convert from string to decimal and when building the query use the CultureInfo.InvariantCulture to convert back to string with "." (period).
HTH
To solve the issue, i used a not so correct code but here is what i did.
string ammount = (textBox2.Text).Replace (",",".");
and i insert the value as string. When the value is passed to the sql statement:
string initialquery = "INSERT INTO EXPENSES (ID, E_DATE, AMMOUNT, PERSON, COMMENTS, T_ID) " +
"VALUES ('" + id + "', '" + date.ToString("yyyy:MM:dd") + "', '" + ammount + "', '" + person + "', '" + comments + "', '" + tid + "')";
and its working