VC++平台下利用Native Client接口接供的OLE DB方法访问SQL SERVER数据库,其它数据类型都容易处理,主要就是处理时间不容易搞清楚,先查询OLE DB与SQL SERVER数据的对应关系,详读以下链接:
我们要插入包括毫秒的日期时间,格式为:
'yyyy-mm-dd hh:mm:ss[.999]'
注意,毫秒与日期时间的隔开符号为一点(.),而不是冒号(:)。
C++平台下使用了时间结构:SYSTEMTIME,包括毫秒,而OLE DB的日期时间格式结构为:
typedef struct tagDBTIMESTAMP
{
SHORT year;
USHORT month;
USHORT day;
USHORT hour;
USHORT minute;
USHORT second;
ULONG fraction;
} DBTIMESTAMP;
注意毫秒的处理,fraction为10亿分之一秒。同时,参数设置时,有这么一句说明:
DBTYPE_DBTIMESTAMP (the fraction field is defined by OLE DB as the number of billionths of a second (nanoseconds) and ranges from 0-999,999,999)
When an application specifies DBTYPE_DBTIMESTAMP in wType, it can override the mapping to datetime2 by supplying a type name in pwszTypeName. If datetime is specified, bScale must be 3. If smalldatetime is specified, bScale must be 0. If bScale is not consistent with wType and pwszTypeName, DB_E_BADSCALE is returned.
If datetime is specified, bScale must be 3. 这一句说明,使用datetime 时,bScale 必须设定为3,则OLE DB访问参数设置为:
typedef struct tagDBPARAMBINDINFO
{
LPOLESTR pwszDataSourceType;
LPOLESTR pwszName;
DBLENGTH ulParamSize;
DBPARAMFLAGS dwFlags;
BYTE bPrecision;
BYTE bScale;
} DBPARAMBINDINFO;
上面结构中,bScale必须设定为3。
这样SYSTEMTIME转为DBTIMESTAMP就简单了,如下所示:
//-----fraction = 1/1000000000 (s)
//-----1/1000000000 (s)=1/1000000 (ms)
void CDataAccess::GetAsDBTIMESTAMP(const SYSTEMTIME& systime,DBTIMESTAMP& dbDateTime)
{
dbDateTime.year = systime.wYear;
dbDateTime.month = systime.wMonth;
dbDateTime.day = systime.wDay;
dbDateTime.hour = systime.wHour;
dbDateTime.minute = systime.wMinute;
dbDateTime.second = systime.wSecond;
__int64 fraction = systime.wMilliseconds*1000000; //就这一句
dbDateTime.fraction = fraction;
}
绑定参数时指定DBTYPE_DBTIMESTAMP,大小提定为sizeof(DBTYPE_DBTIMESTAMP)。
关于Natilve Client使用OLEDB访问数据库的其它细节,参见微软件相文文档: