您的位置:首页 > 数据库 > Oracle

Oracle数据库有关时间操作用法

2014-03-03 20:50 363 查看
#include <afx.h>
#include "CDBOperation.h"
#include <iostream>
#include <afxinet.h>
#include <afxwin.h>
#undef   UNICODE
using namespace std;
void main()
{
CDBOperation dbObject;
CString sql;
bool bConn = dbObject.ConnToDB();
if (true == bConn)
{
cout<<"数据库连接成功...."<<endl;

}
_RecordsetPtr pRst=NULL;  //创建一个数据集智能指针
pRst.CreateInstance(__uuidof(Recordset));//初始化Recordset指针
char type;
while(true)
{
cout<<"请输入查询日期:"<<endl;
//CString tm = "2000年04月05日";
char a[20];
cin.getline(a,20);//输入查询日期
string str(a);
int year,month,day;
string::size_type pos1,pos2;
pos1 = str.find_first_of('-');
year = atoi(str.substr(0, pos1).c_str());
pos2 = str.find_last_of('-');
month = atoi(str.substr(pos1+1, pos2).c_str());
day = atoi(str.substr(pos2+1, pos2+3).c_str());
printf("%d年%d月%d日 \n",year,month,day);

char str[20];
cout<<"请输入查询日期(例如:1990-1-1):"<<endl;
cin.getline(str,20);
CString tm1(str);
//CTime tm = CTime::GetCurrentTime();//获取系统当前时间
//CString tm_str=tm.Format("%Y-%m-%d  %H-%M-%S");

//sql="insert into RECV_TABLE (SID,CONTENT,TIME) values ('S1111','北京大学',to_date('"+tm_str+"','yyyy-mm-dd hh24:mi:ss'))";
sql= "select * from recv_table  rt WHERE (to_char(rt.time,'yyyy-mm-dd'))='"+tm1+"' ";
pRst = dbObject.ExecuteWithResSQL(sql);
if (NULL == pRst)
{
printf("查询数据出现错误!\n");
break;
}
if (pRst->adoEOF)
{
pRst->Close();
printf("There is no records in this table...\n");
break;
}
_variant_t vTime;
if(!pRst->BOF)
{
pRst->MoveFirst();//记录集指针移动到查询结果集的前面
}
while (!pRst->adoEOF)
{
vTime = pRst->GetCollect(_variant_t("TIME"));
pRst->MoveNext();
if(vTime.vt != VT_NULL)
{
cout<<(LPCTSTR)(_bstr_t)vTime<<endl;
}
}
//sql = "select * from recv_table time = to_date('"+tm+"','yyyy-mm-dd hh24:mi:ss')";

if(cin.get() =='e')
{
exit(1);
}

}

system("PAUSE");

}


假如我现在有一个表my_table,其中有一些字段,比如:time字段,其格式为date类型;

--插入当前时间 (时分秒)

insert into
my_table(time) values(sysdate);

--按一定格式插入时间

insert into
my_table (time) values(TO_DATE('2012-11-10 12:34:40','yyyy-mm-dd HH24:MI:SS'));

select to_char(sysdate,'yyyy-mm-dd') as now from dual;

--查询年

select * from
my_table mt where (to_char(mt.time,'yyyy'))='2011';

--查询年月

select * from
my_table mt where (to_char(mt.time,'yyyy-mm'))='2011-11';

--查询年月日

select * from my_table mt where (to_char(mt.time,'yyyy-mm-dd'))='2013-01-10';

--查询年月 ---> 年月

select * from my_table mt where to_char(mt.time, 'yyyy-mm ')> = '2012-01' and to_char(mt.time,
'yyyy-mm ') <= '2012-07 ';

--查询年月日 ---> 年月日

select * from my_table mt where to_char(mt.time,
'yyyy-mm-dd ')> = '2012-01-10 ' and to_char(mt.time,
'yyyy-mm-dd ') <= '2012-07-10 ';
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: