环境: win7 SqlServer2008
前提:SqlServer中设置用户和权限 配置ODBC
功能:向数据库中的dbo.stuinfo表插入数据,并将表中所有数据显示出来
#include "stdafx.h"
#include <string>
#include <iostream>
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "EndOfFile")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitialize(NULL);
_ConnectionPtr m_pConnection=NULL;
_RecordsetPtr m_pRecordset=NULL;
m_pConnection.CreateInstance(__uuidof(Connection));
m_pRecordset.CreateInstance(__uuidof(Recordset));
_bstr_t strConnect ="DSN=Sql_test;Database=studentinof;UID=SQL_RW;PWD=123456;";
_bstr_t bstrSQL("select * from dbo.stuinfo");
char *insert="INSERT INTO [studentinof].[dbo].[stuinfo]([学号] ,[姓名],[性别] ,[民族] ,[班级],[专业]) VALUES('1003',N'张单',N'男',N'回族','2',N'经济')";
_variant_t number,name,sex,nation,grade,major;
string str,str1,str2,str3,str4,str5;
try
{
m_pConnection->Open(strConnect, "","", adModeUnknown);//连接数据库
m_pConnection->Execute(insert,NULL,1);//数据库插入语句
m_pRecordset->Open(bstrSQL, m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
while (!m_pRecordset->EndOfFile)
{
number = m_pRecordset->GetCollect("学号");
name = m_pRecordset->GetCollect("姓名");
sex = m_pRecordset->GetCollect("性别");
nation = m_pRecordset->GetCollect("民族");
grade = m_pRecordset->GetCollect("班级");
major = m_pRecordset->GetCollect("专业");
str = (_bstr_t)number.bstrVal;
str1 = (_bstr_t)name.bstrVal;
str2 = (_bstr_t)sex.bstrVal;
str3 = (_bstr_t)nation.bstrVal;
str4 = (_bstr_t)grade.bstrVal;
str5 = (_bstr_t)major.bstrVal;
cout<<str<<" "<<str1<<" "<<str2<<" "<<str3<<" "<<str4<<" "<<str5<<" "<<endl;
m_pRecordset->MoveNext();
}
m_pRecordset->Close();
}
catch (_com_error e)
{
cout<<"error!"<<endl;
return 0;
}
if(m_pConnection->State)
{
m_pConnection->Close();
}
::CoUninitialize();
return 0;
}