An inconsistent problem of Try-Catch in SQL command, executed in C# - c#

I use Try-Catch to skip some error-prone SQL command in C# but I sometimes still get an execution/runtime error.
My C# code to work with a SQL server database will run frequently. On the first run, there's somewhere in my code that I try to update a table which doesn't exist yet (Later on in the code the table in discussion will be created). I put the part of query in a try-catch, but sometimes still get the error that Invalid object name 'destination_table'.
My code is like this:
string query_str =
" BEGIN TRY " +
" UPDATE [my_DB].[dbo].[destination_table] " +
" SET the_column = 'the_value' " +
" END TRY " +
" BEGIN CATCH " +
" END CATCH ";
using (SqlCommand my_command = new SqlCommand(query_str , conn))
{ form_rack_command.ExecuteNonQuery(); }
The solutions in this link seem good SQL: Try/Catch doesn't catch an error when attempting to access a table that it can't find
But my problem is that I can't always reproduce the error. It seems like sometimes when I start my computer and open Microsoft Visual Studio, I get the error on the first run of the program. But not even shutting down the system and restart everything can always cause the error.
What can be the reason that sometimes I have this problem and sometimes not?

Related

Exception thrown whilst inserting data into an access database using the command "insert into"

I'm working on a project for a college course I'm currently on and I'm having some trouble trying to insert data into a database from an application developed in Visual Studio 2017. I've already connected to the database and am able to open it from the application.
The issue arises when I try to enter data into the table. I get a syntax error. Usually this means there an issue with the actual command right? Well i thought about this and created a new database, and another project and got the inert into command working for that one. At this point , a week of trying to get it to work, I'm stuck and desperately need help. Here is the code I'm using to try and add data to the table.
try
{
Form1.DataBaseConnection.Open();
}
catch (Exception E)
{
MessageBox.Show("!!ATTENTION!! - Error accessing database. Please restart the application. ::::" + E.ToString());
Form1.DataBaseConnection.Close();
}
OleDbCommand DataBaseAddEntry = new OleDbCommand();
DataBaseAddEntry.Connection = Form1.DataBaseConnection;
DataBaseAddEntry.CommandText = "insert into Shoe(Size, Type, Name) values('" + int.Parse(TxtBoxSize.Text) + "','" + TxtBoxType.Text + "','" + TxtBoxName.Text + "')";
DataBaseAddEntry.ExecuteNonQuery();
Form1.DataBaseConnection.Close();
RefreshDataGridView();
As a side not, I didn't design the database or create it. I have to work in a team and the database was created by another member. So when I created my own database it worked fine. Could it be something to do with the actual database and not the code?
Try removing the single quotes from the value for Size, as this looks like it should be an int types.
DataBaseAddEntry.CommandText = "insert into Shoe([Size], [Type], [Name]) values(" + int.Parse(TxtBoxSize.Text) + ",'" + TxtBoxType.Text + "','" + TxtBoxName.Text + "')";
Also, as the comment suggests, you should use parameterized SQL and consider wrapping the try block over the whole database operation, and not only the attempt to open.

Error when inserting DateTime objects with C# code into Access Database 2016

I am trying to insert some calendar dates into an Access database using C#. Unfortunately, it is not working for some reason. The problem is the code is running absolutely perfectly on the computers found in my high school, which are running Office 2007, Windows 7. When I run the same code on my Windows 10 laptop, I get the error:
System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.'
However, the calendar dates are set in the short format, in the database.
I have already tried to convert the strings I am attempting to insert into the database. Some of the conversions I have tried are:
Convert.ToDateTime(itemi[1]);
DateTime.Parse(itemi[2]);
DateTime.ParseExact(itemi[2], "d", null);
Where itemi[2] is one of the strings which are written in calendar date format.
For example: itemi[2] = "02.05.2017"; or itemi[2] = "05.08.2019";
I have also tried to change the . characters found in the itemi[2] string with / characters, with no success. I have even tried to use the Trim() function, in order to make sure the string does not have any blank spaces in it. My professor could not find any solution for this issue, as well, and we looked over the code for hours and searched the internet with no result.
Here is the code with the described issue (the connection to the database has already been opened a few lines of code before, but I consider this to be irrelevant, so I do not include it in the mentioned code):
var query = "INSERT INTO Planificari (Frecventa, DataStart, DataStop, IDLocalitate) "
+ "VALUES ('" + itemi[1].Trim() + "', '" + itemi[2].Trim()
+ "', '" + itemi[3].Trim() +"', " + idLocalitate + ")";
OleDbCommand command = new OleDbCommand(query, connection);
command.ExecuteNonQuery(); // this is the point I get the mentioned error
// DataStart and DataStop are the calendar dates
// in my access 2016 database

Console.WriteLine Endpoint in Console/Log

So, I'm fairly certain this is a relatively remedial question with a likely simple solution, but I just can't seem to find it. I've currently got a program that writes the variables it sets to the console on execution, as well as writing them to the logfile when called through Autosys.
Console.WriteLine(DateTime.Now.ToString("hh:mm:ss.fff") + " Output Variable: " + variable1);
Console.WriteLine(DateTime.Now.ToString("hh:mm:ss.fff") + " Output Variable: " + variable2);
Console.WriteLine(DateTime.Now.ToString("hh:mm:ss.fff") + " Output Variable: " + variable3);
Simple stuff. But for some reason, when I call this...
Console.WriteLine(DateTime.Now.ToString("hh:mm:ss.fff") + " Endpoint: " + endpointAddress);
after previously setting
endpointAddress = "https://endpointaddress.com";
for debug
or
string endpointAddress = Environment.GetEnvironmentVariable("ENDPOINT");
for the Autosys call, with ENDPOINT set in the jobvars file to
JV_ENDPOINT https://endpointaddress.com
and JV_ENDPOINT set in the cmd file to
SET ENDPOINT=%JV_ENDPOINT%
with the end result of it pretty much being exactly the same as it is when the program is run through Visual Studio or the executable itself,
Console.WriteLine(DateTime.Now.ToString("hh:mm:ss.fff") + " Endpoint: " + endpointAddress);
is just skipped entirely in the log. The other ten or so WriteLines that are called all work fine, but nothing at all is written in that line's place.
A few lines up in the log file, I get
D:\server_apps\PROCESS_FOLDER>SET ENDPOINT=https://endpointaddress.com
showing that the endpoint is properly set, but not calling it later.
And...this just in...the most recent time I have run it, the endpoint line just WAS put into the log file. Huh. Well, let's adjust this question a bit. Would anyone happen to have any idea why this particular line might be so uniquely temperamental? I haven't changed anything significant in more than an hour, so I can't fathom why it would suddenly work. But any insight into why it may have happened (and why it might not again) could go a long way toward working any bugs or kinks out of this. Hopefully.
As always, thanks for your time!

How can I get the actual SQL that caused an SqlException in C#? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Obtain the Query/CommandText that caused a SQLException
I am working on some error handling code (using elmah) and the default setup only sends the error message. I would like to know the actual SQL that throws an error (i.e. "SELECT * FROM thisTableDoesNotExist")
This is what I have so far:
if (e.Error.Exception is SqlException)
{
//if SQL exception try to give some extra information
SqlException sqlEx = e.Error.Exception as SqlException;
e.Mail.Body = e.Mail.Body + "<div>" +
"<h1>SQL EXCEPTION</h1>" +
"<b>Message</b>: " + sqlEx.Message +
"<br/><b>LineNumber:</b> " + sqlEx.LineNumber +
"<br/><b>Source:</b> " + sqlEx.Source +
"<br/><b>Procedure:</b> " + sqlEx.Procedure +
"</div>";
}
And I would like to be able to also show the actual SQL. The database is SQL Server 2008 and SqlException is of type System.Data.SqlClient.SqlException.
Not possible. You'll need to catch the exception where the SQL command was executed, and then include your command text in your own custom exception. See Obtain the Query/CommandText that caused a SQLException.
You could have error handling code in your SQL, and when it encounters an error, you can send back the SQL that it attempted to run with a print or returns statement or however you want to return it to your application.
The best way to examine the exception is to put a breakpoint in your code where the exception happens and examine the values of the exception object graph.
Try the Message member of the InnerException like this:
sqlEx.InnerException.Message
It may not provide the exact SQL that failed but may give you more specific information such as the operation and the table name. The StackTrace member may also have some information.
If you can't get enough information on C# side you can use "SQL profiler" (part of complete MS SQL) to see what commands where executed.
Information on SQL Profiler http://msdn.microsoft.com/en-us/library/ms181091.aspx . You should also be able to use underlying Tracing API if you don't have profiler - http://msdn.microsoft.com/en-us/library/ms191006.aspx

Getting a sqlexception on successful insert, VB.NET

I'm trying to do a very simple INSERT using VB.NET. For some reason I'm getting a SqlException on every insert though. The data is inserted, but still get the following:
Violation of PRIMARY KEY constraint 'PK_User'. Cannot insert duplicate key in object 'dbo.Employee'. The statement has been terminated
When I check in SQL Management Studio, the data is succesfully inserted.
Here is the code where the problem is happening
Try
conn.Open()
Dim insertSQL As String = "insert into Employee(uName, firstName, lastName,
On_Switch, On_Phone) " + "values('" & uName & "', '" & firstName & "', '" _
& lastName & "', '" & onSwitch & "', '" & onPhone & "')"
Dim AddCom As SqlCommand = New SqlCommand(insertSQL, conn)
If (AddCom.ExecuteNonQuery() = 1) Then
lblError.Text = "User Added."
' string urlBack = "../ViewAsset.aspx?DeptID=" + DeptID;
' Response.Redirect(urlBack);
End If
conn.Close()
Catch ex As SqlException
Dim ExMsg As String = ex.Message.ToString()
lblError.Text = ExMsg
I went back and tested the same code in C# and there is no Exception thrown. It seems to be something small I'm doing in VB, but I'm lost as to what it is.
As a side note, I STRONGLY recommend changing to parameterized queries to prevent the risk of SQL injection that your current code is not protected from.
For the error issue, I would check to see that your code isn't being called twice in the VB version.
Two theories. Either your code is being executed twice, or there's a trigger on the Employee table that's attempting an insert following the successful insert. (Edit: #Mitchel Sellers is exactly right, if the same code works in c# it's absolutely not a trigger issue.)
My hunch is that your code is being executed twice. Try running with the debugger attached and a breakpoint set on the ExecuteNonQuery - I think you'll find that some other method calls this method multiple times.
#Mitchel Sellers - GOOD CATCH ON THE SQL INJECTION BUG! Parameters, please!
As another side note, I noticed that your code could potentially leave a sql connection open. If you're using the .NET 2.0 framework you should use the Using statement. It ensures that connections are closed and disposed even if an exception is thrown. Check this article on MSDN for more detail: http://msdn.microsoft.com/en-us/library/htd05whh.aspx. The other option would be to add the close statement in a Finally block of your try-catch handler.
If you are executing this code within an event of some sort make sure you have not subscribed to the event multiple times. I have had this problem in asp.net. Usually I just delete the click event handler in the code behind and the onclick attribute in the aspx file if it exists there as well and then try it again.

Categories