I’m currently using C# to try and execute queries on a SQL database. The SELECT query works fine but the INSERT one doesn’t.
I’ve launched the same query from SQL Server manager itself and it works fine but when I send it from the C# (using an ASP page with text boxes to specify the values being sent for the columns) the page simply refreshes and doesn’t show any errors.
The fact that the SELECT query works tells me that server connects fine and that it isn’t the problem. I’ve used breakpoints in the C# code to check if the variables send correctly from the text boxes and they are they should be.
Any ideas what’s going wrong?
Here’s the Code:
protected void SendMyData_OnClick(object sender, EventArgs e)
{
//(NO RECORD SET IS NEEDED IN THIS FUNCTION SEEING AS HOW WE'RE NOT FETCHING ANYTHING)
SqlConnection conServer = new SqlConnection(CDatabase.ConnectionString());
// Database variables
string Track_Name = TextBox8.Text;
string Track_No = TextBox10.Text;
long TN = Convert.ToInt64(Track_No);
string Artist_ID = TextBox11.Text;
long ArtID = Convert.ToInt64(Artist_ID);
string Album_ID = TextBox12.Text;
long AlbID = Convert.ToInt64(Album_ID);
//SUB THESE INTO THE SQL QUERY
try
{
string qrySQL = string.Format("INSERT INTO Tracks ([Track_Name],[Track_No],[Artist_ID],[Album_ID]) VALUES ({0}, {1}, {2}, {3})", Track_Name, TN, ArtID, AlbID);
//This is the string Used to send (Note the NonReturn(As we aren't fetching anything) : " conServer.Open();CDatabase.ExecuteNonReturnQuery(qrySQL);"
conServer.Open();
//(NO RECORD SET IS NEEDED IN THIS FUNCTION SEEING AS HOW WE'RE NOT FETCHING ANYTHING)
CDatabase.ExecuteNonReturnQuery(qrySQL);
}
catch
{
}
finally
{
conServer.Close();
}
Well, there are at least two things seriously wrong here:
SqlCommand.Parametersfor an example.)My guess is that it is throwing an exception due to the track name neither being parameterized nor quoted – you’ve got an arbitrary string in the middle of your SQL.
Catching all exceptions is almost always wrong, and particularly at this level. Usually you should let exceptions propagate up to higher levels, where you may well have a top-level catch-all block for “something went wrong with the request and we don’t want to bring down the whole server” – ASP.NET supplies one of these for you, of course, and allows you to specify how errors should be handled.
Additionally, rather than explicitly closing the SQL connection, I would wrap the whole thing in a
usingstatement (and only after parsing the input, too).Finally, your variable naming is inconsistent – sometimes you’re using
camelCaseand sometimes you’re usingPascalCase. It’s unusual to see Pascal cased variables, to be honest – likewise variables with underscores in. Abbreviating “Artist” and “Album” to “Art” and “Alb” just makes the code less readable too.