1.sql启用windows+SQL双重验证,一般用户名为sa,密码自己设定,登陆状态设定为启动,强制密码策略设置为取消
2.控制面板添加ODBC数据源(不是SQL SERVER,而是名字长的那个)
3.VS添加SQL.h,需要添加如下代码:注意CString 类可以用atlstr
#include "iostream"
#include "atlstr.h"
#include "windows.h"
using namespace std;
#import "C://Program Files//Common Files//System//ado//msado15.dll" no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF")//引入ADO库
//自定义数据库类,如AdoSql
class AdoSql
{
public:
AdoSql();
virtual ~AdoSql();
void InitialConn(); //连接数据库
void ExitConn(); //断开数据库
void GetRecordSet(CString bstrSqlCmd); //获得记录集
void ExcuteCmd(CString bstrSqlCmd); //执行sql语句
public:
_bstr_t m_bstrConn; //存储连接数据库的字符串
_bstr_t m_sqlCmd; //存储sql语句
_ConnectionPtr m_pConnection; //连接数据库对象指针
_RecordsetPtr m_pRecordSet; //数据集对象指针
};
4.添加SQL.cpp,添加如下代码
#include "SQL.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
AdoSql::AdoSql()
{
m_pConnection = NULL;
m_pRecordSet = NULL;
InitialConn();
}//构造函数
AdoSql::~AdoSql()
{
}//析构函数
void AdoSql::InitialConn()
{
//初始化COM组件
::CoInitialize(NULL);
HRESULT hr = NULL;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection"); //创建Connection对象
//hr = m_pConnection.CreateInstance(__uuidof(Connection));作用同上
//1、新建一个文件,名字任意取,后缀名必须为udl(如何hello.udl)
//2、双击hello.udl文件,进入数据连接属性面板,填写好数据源(选择自己创建的数据源名字的)
//3、再以记事本方式打开,第三行的数据就是连接字符
//m_bstrConn = "Provider=SQLNCLI10.1;Integrated Security="";Persist Security Info=False;User ID=sa;Password=123456;Initial Catalog=WORK;Data Source="";Initial File Name="";Server SPN=""";
m_bstrConn = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=PSINS;Data Source=阿破";
//连接数据库的字符串
hr = m_pConnection->Open(m_bstrConn, "sa", "106662", adModeUnknown);//登陆
if (!SUCCEEDED(hr)) {
printf("连接数据库失败");
}
}
catch (_com_error e)
{
CString strErr;
strErr.Format(L"连接数据库失败\n%s", e.ErrorMessage());
}
}
void AdoSql::GetRecordSet(CString bstrSqlCmd)
{
m_sqlCmd = _bstr_t(bstrSqlCmd);
m_pRecordSet.CreateInstance(__uuidof(Recordset));//创建记录集指针对象实例
m_pRecordSet->Open(m_sqlCmd, m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);//打开记录集
}
void AdoSql::ExcuteCmd(CString bstrSqlCmd)
{
m_sqlCmd = _bstr_t(bstrSqlCmd);
_variant_t RecordsAffected;
try {
m_pRecordSet = m_pConnection->Execute(m_sqlCmd, &RecordsAffected, adCmdText);
}
catch (_com_error e) {
}
}
void AdoSql::ExitConn()
{
//关闭记录集和连接
if (m_pRecordSet != NULL)
{
m_pRecordSet->Close();
}
m_pConnection->Close();
::CoUninitialize();
}
注意连接数据库所用的字符串,按代码中的三步操作
5.在需要操作数据库的文件里定义数据库对象:
#include"SQL.h"
AdoSql adoSql;//类AdoSql的对象
6.数据库操作:
CString strCmd;
strCmd.Format(L"insert into psins (datasets,timeStart,timeEnd,t_nogps) values('%s','%f','%f','%f')", dataDir, t_start, t_end, no_gps_time);
adoSql.InitialConn();
adoSql.ExcuteCmd(strCmd);
adoSql.ExitConn();