[英]How to use date data type in either MS Access or SQL Server when using ODBC connection
I have a program in C# which connects to a database using a DSN (ODBC driver). 我有一个C#程序,它使用DSN(ODBC驱动程序)连接到数据库。
All queries I run in the program uses SQL. 我在程序中运行的所有查询都使用SQL。 All works well but when using datetime data type in queries (in SELECT statement or in WHERE clause).
一切都很好,但是在查询中(在SELECT语句或WHERE子句中)使用日期时间数据类型时。
When DSN is a MS ACCESS database, I have to use something like this: 当DSN是MS ACCESS数据库时,我必须使用如下所示的内容:
WHERE SomeDate = #1/1/2005#
But if the same database is in SQL Server, i should use something like this: 但是,如果同一数据库位于SQL Server中,则应使用如下所示的内容:
WHERE SomeDate = '1/1/2005'
Is there a way to manage this in the same program without doing a routine for SQL Server and another for MS ACCESS? 有没有一种方法可以在同一程序中进行管理,而无需为SQL Server和MS ACCESS编写例程?
I tried by getting properties of OdbcConnection object, but I could not find a way to detect if driver is MS Access or SQL Server. 我尝试通过获取OdbcConnection对象的属性来进行尝试,但是找不到找到驱动程序是MS Access还是SQL Server的方法。
You probably have used data type Datetime2 in SQL Server. 您可能在SQL Server中使用了数据类型Datetime2 。 That will be read as text if using the native SQL Server ODBC driver.
如果使用本机SQL Server ODBC驱动程序,则将其作为文本读取。
So either: 所以:
Microsoft® ODBC Driver 17 for SQL Server® 用于SQLServer®的Microsoft®ODBC驱动程序17
You can set your Access database to be in ANSI-92 mode. 您可以将Access数据库设置为ANSI-92模式。 This will allow you to query date fields with single quotes.
这将允许您查询带单引号的日期字段。
A word of warning though if this is an existing database or there are other applications using it. 尽管这是一个现有数据库,或者有其他应用程序在使用它,但请注意。 This may introduce a breaking change to any existing queries in your database that are not ANSI compliant.
这可能会对数据库中不符合ANSI标准的任何现有查询带来重大更改。 Likewise, if there are other applications using this database their queries may also break.
同样,如果还有其他使用此数据库的应用程序,其查询也可能会中断。
Also as an alternative, please note that OdbcConnection
does have a Driver
property that you can probe to determine the data source. 另外,请注意,
OdbcConnection
确实具有一个Driver
属性,您可以对其进行探测以确定数据源。 On my machine, a DSN pointing to a SQL Server database returns sqlncli11.dll
, because I am using the SQL Server Native Client 11.0. 在我的计算机上,指向SQL Server数据库的DSN返回
sqlncli11.dll
,因为我使用的是SQL Server Native Client 11.0。 You can use this property to drive the syntax of your queries in your application. 您可以使用此属性来驱动应用程序中查询的语法。 You could create a data access layer that abstracts some of this away from the rest of your code.
您可以创建一个数据访问层,将其中的某些部分与其余的代码抽象化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.