c/c++怎么连接数据库,并执行SQL语句

2024-04-27

1. c/c++怎么连接数据库,并执行SQL语句

C++连接SQL数据库第一步 系统配置
1.设置SQLSERVER服务器为SQL登录方式,并且系统安全性中的sa用户要设置登录功能为“启用”,还有必须要有密码。
2.需要在ODBC中进行数据源配置,数据源选\”SQL SERVER”,登录方式使用“使用输入用户登录ID和密码的SQL SERVER验证”,并填写登录名(sa)和密码,注意一点,密码不能为空,这就意味着你的sa用户必须得有密码。否则无法通过系统本身的安全策略。测试通过就完成了配置。
C++连接SQL数据库第二步 C++与SQL连接初始化
1.在你所建立的C++项目中的stdafx.h头文件中引入ADO
具体代码如下
#import “c:\Program Files\Common Files\System\ado\msado15.dll” 
no_namespace rename(”EOF”, “adoEOF”) rename(”BOF”, “adoBOF”) 
2.定义_ConnectionPtr变量后调用Connection对象的Open方法建立与服务器的连接。
数据类型_ConnectionPtr实际上是由类模板_com_ptr_t得到的一个具体的实例类。_ConnectionPtr类封装了Connection对象的Idispatch接口指针及其一些必要的操作。可以通过这个指针操纵Connection对象。
例如连接SQLServer数据库,代码如下:
//连接到MS SQL Server  
//初始化指针  
_ConnectionPtr pMyConnect = NULL;  
HRESULT hr = pMyConnect.CreateInstance(__uuidof(Connection));  
if (FAILED(hr))  
return;  
//初始化链接参数  
_bstr_t strConnect = “Provider=SQLOLEDB; 
Server=hch; 
Database=mytest; 
uid=sa; pwd=sa;”; //Database指你系统中的数据库  
//执行连接  
try  
{  
// Open方法连接字串必须四BSTR或者_bstr_t类型  
pMyConnect->Open(strConnect, “”, “”, NULL);  
}  
catch(_com_error &e)  
{  
MessageBox(e.Description(), “警告”, MB_OK|MB_ICONINFORMATION);  
}//发生链接错误

C++连接SQL数据库第三步 简单的数据连接
//定义_RecordsetPtr变量,调用它Recordset对象的Open,即可打开一个数据集  
//初始化过程 以下是个实例  
_RecordsetPtr pRecordset;  
if (FAILED(pRecordset.CreateInstance(__uuidof(Recordset))))  
{  
return;  
}  
//执行操作  
try  
{  
pRecordset->Open(_variant_t(”userinfo”), 
_variant_t((IDispatch*)pMyConnect),  
adOpenKeyset, adLockOptimistic, adCmdTable);  
}  
catch (_com_error &e)  
{  
MessageBox(”无法打开userinfo表\”, “系统提示”, 
MB_OK|MB_ICONINFORMATION);  
}

C++连接SQL数据库第四步 执行SQL语句
这里是关键,我认为只要你懂点SQL语句那么一切都会方便许多比用上面的方法简单,更有效率点。
首先
m_pConnection.CreateInstance(_uuidof(Connection)); 
//初始化Connection指针  
m_pRecordset.CreateInstance(__uuidof(Recordset));
//初始化Recordset指针  
CString strSql=”select * from tb_goods”;//具体执行的SQL语句  
m_pRecordset=m_pConnection->Execute(_bstr_t(strSql), 
NULL, adCmdText);//将查询数据导入m_pRecordset数据容器 
至此 你的SQL语句已经执行完成了m_pRecordset内的数据就是你执行的结果。
取得记录:
while(!m_pRecordset->adoEOF)//遍历并读取name列的记录并输出  
{  
CString temp = (TCHAR *)(_bstr_t)m_pRecordset->GetFields()->GetItem  
(”name”)->Value;  
AfxMessageBox(temp);  
pRecordset->MoveNext();  
}

插入记录
//记得初始化指针再执行以下操作  
CString strsql;  
strsql.Format(”insert into tb_goods(no,name, price) 
values(’%d’,'%s’, %d)”,m_intNo,m_strName,m_intPrice);  
m_pRecordset=m_pConnection->
Execute(_bstr_t(strsql),NULL,adCmdText);

修改记录
CString strsql;  
strsql.Format(”update tb_goods set name=’%s’ , 
price=%d where no=%d “,m_strName,m_intPrice,m_intNo);   
m_pRecordset=m_pConnection->Execute(_bstr_t(strsql),NULL,adCmdText);

删除记录
CString strsql;  
strsql.Format(”delete from tb_goodswhere no= ‘%d’ “,m_intNo);  
m_pRecordset=m_pConnection->Execute(_bstr_t(strsql),NULL,adCmdText)

c/c++怎么连接数据库,并执行SQL语句