I tried searching for a similar answer here on stackoverflow, but I might just be bad at searching. I'm relatively new to c#, and what I'm trying to do is loop through different ID's so I can use a prepared statement in SQL server to run a series of queries, looping through those different ID's. I tired using a while loop, but I may have done it incorrectly and I'm not certain. I know how to use SQL server, that's not the issue as I have that working there just fine, but I want to try to use it in C# for different testing purposes. Here is my code:
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main()
{
Console.WriteLine("Executing query...");
int i = 46556;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
using (SqlConnection connection = new SqlConnection("CONNECTION_STRING"))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT TOP 100 GlobalCustomerVehicleID, GlobalCustomerID, Status, VIN, LastEditByUserID, CreatedByUserID, Year, Make, Model FROM Drop_GlobalCustomerVehicle WHERE GlobalCustomerID = @ID", connection))
{
command.Parameters.Add(new SqlParameter("ID", i));
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int GlobalCustomerVehicleID = reader.GetInt32(0);
int GlobalCustomerID = reader.GetInt32(1);
string Status = reader.GetString(2);
string VIN = reader.GetString(3);
int LastEditByUserID = reader.GetInt32(4);
int CreatedByUserID = reader.GetInt32(5);
short Year = reader.GetInt16(6);
string Make = reader.GetString(7);
string Model = reader.GetString(8);
Console.WriteLine("GlobalCustomerVehicleID = {0}, GlobalCustomerID = {1}, Status = {2}, VIN = {3}, LastEditByUserID = {4}, CreatedByUserID = {5}, Year = {6}, Make = {7}, Model = {8}",
GlobalCustomerVehicleID,
GlobalCustomerID,
Status,
VIN,
LastEditByUserID,
CreatedByUserID,
Year,
Make,
Model
);
}
}
}
i = i + 10;
if (i > 47000)
break;
}
stopwatch.Stop();
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
I know some of this isn't exactly super secure, such as the connection string directly inside of the code, but this is only for testing purposes and will not be used outside of internal testing. Could someone tell me where I'm going wrong, or even suggest a fix? Thank you for your time.
Edit: It was a simple fix, and I apologize that my question was too generalized! The question was I was wanting it to actually loop through several times instead of just once. It worked in that it did a single query, but didn't go through the different ID's I was expecting. However, I missed a single 0, and even after searching through my code I just completely missed that very easy mistake. Thank you for pointing it out, and suggesting a more optimal way to write the while loop.
while (true)by the way, just use eitherwhile (i <= 4700)or aforloop