Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

passing date and time to SQL server using C#

Can you please help me:

How do I pass String dateAndTime = "2/2/2012 5:57:00 pm" to SQL server using C#?

I was passing it as a String but obviously SQL does not like the syntax. it gives me an error:

Wrong syntax near 5:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Never pass dates as string, but use the proper datetime datatype. Look up commands and parameters instead of creating SQL statements in code. Google SqlCommand

EDIT: I was on my phone yesterday. Here is a better answer:

int GetNumberOfItemsAfterDate(DateTime dateInput) {
    // Create a sql statement with a parameter (@FirstDate)
    string sql = @"SELECT Count(*)
                   FROM   table
                   WHERE  table.date >= @FirstDate";

    // Create a sql connection
    // Always use the using statement for this
    using (var connection = new SqlConnection(connectionString)) {

        // Create a sql command
        // Always use the using statement for this
        using (var command = new SqlCommand(sql, connection)) {

            // Pass the dateinput argument to the command, and let
            // the .NET Framework handle the conversion properly!
            command.Parameters.Add(new SqlCommand("FirstDate", dateInput));

            // No need for calling .Close() or .Dispose() - the using
            // statements handle that for us
            return (int)command.ExecuteScalar();
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...