0

Hello i have a method which saves some data in the SQL, but sometimes not every parameters are set, this gives me an exception becuase its NULL.

Here is my Method:

 public string getBookingURL(string guid, BookingRequest request, string token, out string exitURL)
    {

        if (validateToken(token))
        {
            string command = "INSERT INTO OUTLOOKADDIN (GUID, TOKEN, BOOKINGID, STARTUTC, ENDUTC, SUBJECT, NUMPARTICIPANTS) VALUES (@GUID, @TOKEN, @BOOKINGID, @STARTUTC, @ENDUTC, @SUBJECT, @NUMPARTICIPANTS)";
            SqlConnection connection = new SqlConnection(GetConnectionString());
            connection.Open();
            try
            {
                SqlCommand cmd = new SqlCommand(command, connection);
                cmd.Parameters.Add("@GUID", guid);
                cmd.Parameters.Add("@TOKEN", token);
                cmd.Parameters.Add("@BOOKINGID", request.bookingID);
                cmd.Parameters.Add("@STARTUTC", request.startUTC);
                cmd.Parameters.Add("@ENDUTC", request.endUTC);
                cmd.Parameters.Add("@SUBJECT", request.subject);
                cmd.Parameters.Add("@NUMPARTICIPANTS", request.numParticipants);
                cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                cmd.Dispose();
                cmd = null;
            }

            catch (Exception ex)
            {
                log.Error(ex.Message + "\n\rStackTrace:\n\r" + ex.StackTrace);
            }
            finally
            {
                connection.Close();
            }

            HttpContext current = HttpContext.Current;
            string baseUrl = current.Request.Url.Scheme + "://"
                + current.Request.Url.Authority
                + current.Request.ApplicationPath.TrimEnd('/');

            exitURL = baseUrl + "/index.html";
            return baseUrl + '/'
                + "WebPage/Booking/BBooking.aspx?"
                + "OPS"
                + guid; ;

        }
        exitURL = null;
        return null;
    }

i think that this SQL Query...

string command = "INSERT INTO OUTLOOKADDIN (GUID, TOKEN, BOOKINGID, STARTUTC, ENDUTC, SUBJECT, NUMPARTICIPANTS) VALUES (@GUID, @TOKEN, @BOOKINGID, @STARTUTC, @ENDUTC, @SUBJECT, @NUMPARTICIPANTS)";

... should run dynamically or is there any other solution which prevents adding the parameter when its empty?

9
  • 1
    What exception are you getting? Commented Feb 22, 2013 at 6:47
  • Can you set your columns as nullable in the database? Commented Feb 22, 2013 at 6:50
  • that the startutc date shuld be between 1900 - 2999... , the datetime is empty Commented Feb 22, 2013 at 6:50
  • i think that the datetime wont accept null, is that right? Commented Feb 22, 2013 at 6:50
  • 2
    Unrelated Tip: If you use using (SqlCommand cmd = ...) { ... } then there is no need to call cmd.Dispose(); and Parameters.Clear() Commented Feb 22, 2013 at 6:52

3 Answers 3

2

In addition to vignesh's post, use DBNull.Value for null values, if the DB fields are nullable.

EDIT: It is probably better to check the values BEFORE you even get to your getBookingURL() method. If you do proper validation before reaching this point then you can avoid the whole problem altogether.

if (/* date is null or not valid */)
    cmd.Parameters.Add("@mydate", SqlDbType.DateTime).Value = DBNull.Value;
else
    cmd.Parameters.Add("@mydate", SqlDbType.DateTime).Value = myDate;
Sign up to request clarification or add additional context in comments.

1 Comment

i tried your code, even if i let the datetime empty it shows me this date: {01.01.0001 00:00:00} how can i use this in my if statement?
1

You can add validation in the front end to prevent empty values

or

you can check for null values before adding parameters

if(value!=null)
{
cmd.Parameters.Add("@GUID", guid);
} 
else
{
cmd.Parameters.Add("@GUID", "somestring or value");
} 

2 Comments

what can i do when a datetime is empty?
you can use the ternary operators in all your command.Parameters.Add for example instead of >> cmd.Parameters.Add("@ENDUTC", request.endUTC) you can use >> cmd.Parameters.Add("@ENDUTC", (request.endUTC == null) ? (object)DBNull.Value : request.endUTC); similarly you can do for adding all the other parameters vote up if you find the above comment useful in someway
0

If your fields in the db table are unnulable, you must validate the values on the front end and show a warningto the user.

If the columns are nullable, you can send the DBNull to the database and it wont throw exception. My solution for it:

cmd.Parameters.AddWithValue("@ParameterName",
            (a == null) ? (object)DBNull.Value : a);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.