|
Start by not doing that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
When you concatenate strings, you cause problems because SQL receives commands like:
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood' The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable; Which SQL sees as three separate commands:
SELECT * FROM MyTable WHERE StreetAddress = 'x'; A perfectly valid SELECT
DROP TABLE MyTable; A perfectly valid "delete the table" command
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.
So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
In this specific case it doesn't expose you to SQL Injection, but it does bring up a different probable problem which may be causing what you have found. When you concatenate strings, you cause an implicit ToString on your DateTime objects which will convert them using the default culture for the computer that is running that code. In most production systems the SQL server is a separate computer (which may not even be in the same country, let alone LAN segment) and that computer may well be configured for a different default date format. So when SQL parse your string, it can very, very easily convert it wrong: you supply dd/MM/yyyy and it reads MM/dd/yyyy for example.
So go through the whole of your app and fix it: remove all string concatenations, replace them with parameterized queries, and see if your problem disappears at the same time...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Once you fix your concatenated SQL, you need to fix your reader loop; there is nothing to differentiate what the start and stop dates are
while (rdr.Read()) {
String sName = rdr["orderID"].ToString();
listBox1Montag.Items.Add(sName);
listBox2Dienstag.Items.Add(sName);
listBox3Mittwoch.Items.Add(sName);
listBox4Donnerstag.Items.Add(sName);
listBox5Freitag.Items.Add(sName);
}
What you need to do is to enumerate through the rows and check to see if the start/finish dates align with a particular day
while (rdr.Read()) {
String sName = rdr["orderID"].ToString();
DateTime StartDate = Convert.ToDateTime(rdr["DateField"]).ToString("dd/MM/yyyy");
DateTime FinalDate = Convert.ToDateTime(rdr["FinalDate"]).ToString("dd/MM/yyyy");
if ((StartDate <= MONDAY) && (FinalDate >= MONDAY)) { listBox1Montag.Items.Add(sName); }
if ((StartDate <= FRIDAY) && (FinalDate >= FRIDAY)) { listBox5Freitag.Items.Add(sName); }
}
Director of Transmogrification Services
Shinobi of Query Language
Master of Yoda Conditional
|
|
|
|
|
Dear all,
I have a folder that including input files (generally 20 to 30 files)
I want to order names when the form loaded on 1st column of listbox.
Thanks
|
|
|
|
|
|
The efficient way to do it is to sort before you add the items:
string[] files = Directory.GetFiles(@"D:\Test Data", "*.*", SearchOption.AllDirectories);
string[] sortedFiles = files.OrderBy(f => Path.GetFileNameWithoutExtension(f)).ToArray();
myListBox.Items.AddRange(sortedFiles);
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
In your example, you're specifying all directories. Wouldn't you do this instead:
string[] files = Directory.GetFiles(@"D:\Test Data", "*.*", SearchOption.AllDirectories)
.OrderBy(f => Path.Getdirectory(f))
.ThenBy(f => Path.GetFileNameWithoutExtension(f))
.ToArray();
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
In the real world? Probably.
It's just an example - I have no idea what he really wants to sort by, the info is a bit sparse!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Eg. File names in folder names ( bb1.txt, bb2.txt, cc1.txt, cc2.txt ....)
When I load the window I want to see txt files names in different rows, sorted on 1 st column.
A
bb1
bb2
cc1
cc2
.
.
.
I think you get the point now
|
|
|
|
|
Nope, still makes no sense! Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with. And I have no idea what folders you have, or what you are trying to do with them.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
In Griff's original answer, change the second parameter in the call to Directory.GetFiles from "*.*" to "*.txt"
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
Hi,
I have a table in SQL like so
UId Class
1 Apple
2 Apple
3 Apple
3a Apple
4 Orange
4a Orange
4b Orange
5 Orange
I am trying to get the min and max of the UId column for each class as below.
1 - 3 Apple
4 - 5 Orange
Is it possible to do so, as the UId is varchar.
Thanks
modified 23-Mar-18 23:41pm.
|
|
|
|
|
sunsher wrote: Is it possible to do so, as the UId is varchar.
Yes, but ... it's frankly pretty nasty, and going to make for a complicated query.
If you want data that you can treat as numeric - and you will need to use it for numerics at some point, or your sort order will be completely wrong - I'd strongly suggest that you change the column, and split it into two parts: a numeric prefix, and an alphabetic suffix. That way, you can ignore your suffix when trying to work with numbers, and combine the columns to a strign when you want to work with the "original value".
Then it's trivial:
SELECT MIN(numericBit), MAX(numericBit), Class
FROM MyTable
GROUP BY Class But trying to do that with string based data that may contain alphabetic suffixes? Nasty, nasty code.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Yes; you require a "transform" part for your "ETL" procedure (extract; transform; "load").
Just like in "big data".
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
I am bluntly going to say that UId isn't. A primary key is not a varchar. I don't care about how you want to display it, it should not be stored like that.
A Guid, fine. Integer, fine. No varchar. Change it to avoid more problems later
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Like Griff said, that would result in some nasty SQL. Of course, the following works just fine:
IF OBJECT_ID('tempdb..#fruits') IS NOT NULL
DROP TABLE #fruits
CREATE TABLE #fruits
(
ID nvarchar(10),
Fruit nvarchar(16)
)
insert into #fruits (ID, Fruit)
VALUES ('1', 'Apple'),
('2', 'Apple'),
('3', 'Apple'),
('3a', 'Apple'),
('4', 'Orange'),
('4a', 'Orange'),
('4b', 'Orange'),
('5', 'Orange')
SELECT MIN([ID]) AS MinID, MAX([ID]) AS MaxID, [Fruit] FROM [#fruits] GROUP BY [Fruit]
SELECT MIN(substring([ID], PATINDEX('%[0-9]%', [ID]), 1+PATINDEX('%[0-9][^0-9]%', [ID]+'x')-PATINDEX('%[0-9]%', [ID]))) AS MinID,
MAX(substring([ID], PATINDEX('%[0-9]%', [ID]), 1+PATINDEX('%[0-9][^0-9]%', [ID]+'x')-PATINDEX('%[0-9]%', [ID]))) AS MaxID,
[Fruit]
FROM [#fruits]
GROUP BY [Fruit]
Beyond that, what if the data is mixed up (the data is put into the database as apple,orange,apple,apple,orange,apple)?
Even if the data WERE ordered exactly the way you want it, what business case would find the min/max Uid as relevant data? Even if you were using a more appropriate integer ID field, it still wouldn't mean anything to anyone.
[Minor_Rant]
Programming instructors really need to start creating meaningful assignments so that a) the student doesn't learn from a basis of bad coding practice, and b) the student isn't pummeled with whacked out scenarios that would never happen in the real world.
The small amount of actual college I attended (after having been a programmer for 10 years) really ticked me off. One C++ assignment involved counting the number of a certain character in a string. I provided three different ways to do it, but I was marked down (I actually got an 'F' for the assignment) for the content of the string I used. I contested it, and got my 'A' grade, but the whole thing left me with a real sour taste in my mouth for "instructors" of any description.
[/Minor_Rant]
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
modified 23-Mar-18 10:48am.
|
|
|
|
|
Slight simplification of the last query:
SELECT
MIN(N.JustNumeric) AS MinID,
MAX(N.JustNumeric) AS MaxID,
F.[Fruit]
FROM
[#fruits] As F
CROSS APPLY ( SELECT substring(F.[ID], PATINDEX('%[0-9]%', F.[ID]), 1 + PATINDEX('%[0-9][^0-9]%', F.[ID] + 'x') - PATINDEX('%[0-9]%', F.[ID])) ) As N (JustNumeric)
GROUP BY
F.[Fruit]
;
Still nasty, but at least the "computed column" doesn't have to be repeated.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
From all the expert adivces I get here, I think I should not do what I intend to do. As it is a ASP.NET Webforms application using VB.NET, I retrieved all the records from the table, and inserted into a dictionary, then played with it. So now I get the result I want.
|
|
|
|
|
If you're working in VB, why did you post your question in the C# forum?
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
To repeat myself; the way you load it is not a problem. The way you store it is; go read up on what a primary key is.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Dude, that's just a thing of beauty right there. Almost as good as a macro.
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
You will also need something like
CONVERT(int, SUBSTRING(F.[ID], PATINDEX('%[0-9]%', F.[ID]), etc))
as otherwise, 10, 11,..., 19, 100, ..., 199 etc will fall between 1 and 2 because you are still comparing as strings
|
|
|
|
|
John Simmons / outlaw programmer wrote: I actually got an 'F' for the assignment) for the content of the string
Using "youareafuckingidiot" as your content will do that.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Well, the instructor did not provide the string (a curiosity because it would have made evaluating the output from code much easier since everyone would have to have the same count), so I wrote a paragraph about the diminishing hemlines in college girls' skirts during summer classes.
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
Can it be done; yes.
Should it be done; not at this time.
Really should fix the database design first.
1. You should have a Good Primary Key. UID in its current state is not.
2. Class should be normalized- put it into its own table and link it back via another Good Primary Key
Director of Transmogrification Services
Shinobi of Query Language
Master of Yoda Conditional
|
|
|
|
|
Hi,
I have he following code which for the line "await GetSkorekortSkore(x.SkorekortID)" is giving the error message "the await operator can only be used within an async lambda expression. Consider marking this lambda expression with the async modifier".
Any suggestion of how to make it work ?
return (from s in _db.SkoreKort
from k in _db.Klub
from b in _db.Bane
where (s.SkorekortID == SkorekortID &&
s.BaneKlubID == k.KlubID &&
s.BaneID == b.BaneID)
select new {
s.SkorekortID,
k.DGUKlubNr,
s.SkoreDato,
s.SpillerHCP,
k.KlubNavn,
b.BaneNavn,
b.TeeNavn,
b.HerreDame,
b.BaneID,
k.KlubID
}).AsQueryable()
.Select(x => new SkorekortDetailViewModel {
SkorekortID = x.SkorekortID,
DGUKlubNr = x.DGUKlubNr,
SkoreDato = x.SkoreDato,
SpillerHCP = x.SpillerHCP,
KlubNavn = x.KlubNavn,
BaneNavn = x.BaneNavn,
TeeNavn = x.TeeNavn,
HerreDame = x.HerreDame,
SkoreListe = await GetSkorekortSkore(x.SkorekortID)
}).ToListAsync();
}
public async Task<List<SkorekortSkore>> GetSkorekortSkore(int SkorekortID)
{
return await (from s in _db.SkoreKortSkore
where s.SkorekortID == SkorekortID
select s).ToListAsync();
}
modified 22-Mar-18 4:00am.
|
|
|
|
|