1.下载SQL Server 2008 R2安装包,并顺利安装(下载和安装过程就不展开说明)。
2.SQL Server配置。
1)点击“开始”->所有程序->Microsoft SQL Server 2008 R2->配置工具->SQL Server 配置管理器
2)点击SQL Server服务。右键选择 SQL Server,点击“启动”
3)点击SQL Server网络配置,选择 SQLEXPRESS的协议,双击TCP/IP->IP地址,进行设置
IP1
IP地址:127.0.0.1
TCP端口:1433
已启用:是(一定要选择“是”,否则启动不了)
IP2
IP地址:自己电脑的IP地址
TCP端口:1433
已启用:是(一定要选择“是”,否则启动不了)
3.到SQL Server Management Studio内设置并更改连接方式。
1)先用windows身份进入到数据库
2)然后在“服务器”名称处单击鼠标右键,选择“属性”
3)在弹出的界面中选择“安全性”,并将“服务器身份验证”更改为“SQL Server 和 Windows 身份验证模式。
4)点击”确定“即可。
4.在SQL Server Management Studio内对 "sa"更改密码并新建数据库。
1)在管理界面单击打开”安全性“,弹出的列表中,双击”sa",更改密码为"sa123"
2)在数据库选项右击,选择新建数据库“student"
5.在服务器名称右击,选择”重启数据库“。
等重启完毕,再次进入数据库时,选择”SQL Server 身份验证“,并用更改后的帐号"sa"和密码”sa123",重新进入。
6.在VC6中新建对话框程序。
并在头文件中申明变量,
_ConnectionPtr pMyConnect;
_CommandPtr pCommand;
_RecordsetPtr pRecordset;
在运行cpp文件中进行如下操作。
//在初始化函数进行如下操作
AfxOleInit();
/
HRESULT hr=pMyConnect.CreateInstance(__uuidof(Connection));
if (FAILED(hr))
{
return;
}
//初始化链接参数
_bstr_t strConnect="driver={SQL Server};\
Server=127.0.0.1,1433;\ /*为服务器IP和端口,端口不可忘记*/
Database=student;\ /*为系统数据库名称*/
uid=sa;\ /*登录帐号*/
pwd=sa123;"; /*登录密码*/
//执行连接
try
{
pMyConnect->Open(strConnect,"","",NULL);
}
catch (_com_error& e)
{
MessageBox(e.Description(),"警告",MB_OK|MB_ICONINFORMATION);
}//发生连接错误
//连接 表
if (FAILED(pRecordset.CreateInstance(__uuidof(Recordset))))
{
return;
}
try
{
pRecordset->Open(_variant_t("s"),_variant_t((IDispatch*)pMyConnect),\
adOpenKeyset,adLockOptimistic,adCmdTable);
}
catch (_com_error& e)
{
MessageBox(e.Description(),"系统提示",MB_OK|MB_ICONINFORMATION);
}
//数据查询
CString strSql="select *from s where sno='1' and sname='name1'";
pRecordset=pMyConnect->Execute(_bstr_t(strSql),NULL,adCmdText);//将查询数据导入pRecordset数据容器
while(!pRecordset->adoEOF)//便利并读取name列的记录并输出
{
_variant_t theValue;
theValue = pRecordset->GetCollect( "sage");
if (theValue.vt!=VT_NULL)
{
CString strTemp=(LPCSTR)_bstr_t(theValue);
TRACE(strTemp+"\n");
}
pRecordset->MoveNext();
}
pRecordset->Close();
//数据更新
CString strSql="UPDATE s SET sname='name1' where sno='1' and sage='1'";
try
{
pRecordset=pMyConnect->Execute(_bstr_t(strSql),NULL,adCmdText);//将查询数据导入pRecordset数据容器
}
catch (_com_error& e)
{
MessageBox(e.Description(),"系统提示",MB_OK|MB_ICONINFORMATION);
}
//新增数据
CString strSql="INSERT INTO s(sno,sname,sage) VALUES('8','name8',8)";
try
{
pRecordset=pMyConnect->Execute(_bstr_t(strSql),NULL,adCmdText);//将查询数据导入pRecordset数据容器
}
catch (_com_error& e)
{
MessageBox(e.Description(),"系统提示",MB_OK|MB_ICONINFORMATION);
}
//删除数据
CString strSql="DELETE FROM s WHERE sno='8'";
try
{
pRecordset=pMyConnect->Execute(_bstr_t(strSql),NULL,adCmdText);//将查询数据导入pRecordset数据容器
}
catch (_com_error& e)
{
MessageBox(e.Description(),"系统提示",MB_OK|MB_ICONINFORMATION);
}
//程序退出时需要关闭连接
pMyConnect->Close();