用VC++如何操作SQL Server数据库

请大家帮帮忙,分别写出以下下代码:(最好使用VS2008+SQLServer2005)
需要包含的头文件。
1.链接数据库
2.建立数据库
3.定义表
4.添加数据
5.删除数据
6.排序
最好有详细的注释。

我是一个数据库的初学者,想写一个信息管理系统,用VC++实现数据库信息的添加、修改、删除,但看了看书,不太懂,希望大家帮帮忙。ODBC\ADO\ 或者其他方法都行,但最好写的详细一点,容易理解。
如果有什么好理解的书也可以告诉我。
不要从别的实例教材或者其他地方复制,那样的我自己也会找。

第1个回答  2009-07-15
1---------------------------------------

#include
#include
#include
#include
#include
#include
#define SNO_LEN 30
#define NAME_LEN 50
#define DEPART_LEN 100
#define SSEX_LEN 5
int main()
{
/* Step 1 定义句柄和变量 */
//以king开头的表示的是连接KINGBASEES的变量
//以server开头的表示的是连接SQLSERVER的变量
SQLHENV kinghenv, serverhenv; //环境句柄
SQLHDBC kinghdbc,serverhdbc; //连接句柄
SQLHSTMT kinghstmt,serverhstmt; //语句句柄
SQLRETURN ret;
SQLCHAR sName[NAME_LEN], sDepart[DEPART_LEN],sSex[SSEX_LEN],sSno[SNO_LEN];
SQLINTEGER sAge;
SQLINTEGER cbAge = 0, cbSno = SQL_NTS, cbSex = SQL_NTS,cbName = SQL_NTS,cbDepart = SQL_NTS;
/* Step 2 初始化环境 */
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &kinghenv);
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &serverhenv);
ret = SQLSetEnvAttr(kinghenv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
ret = SQLSetEnvAttr(serverhenv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
/* Step 3 :建立连接 */
ret = SQLAllocHandle(SQL_HANDLE_DBC, kinghenv, &kinghdbc);
ret = SQLAllocHandle(SQL_HANDLE_DBC, serverhenv, &serverhdbc);
ret = SQLConnect(kinghdbc,
"KingbaseES ODBC",SQL_NTS,
"SYSTEM",SQL_NTS,
"MANAGER",SQL_NTS);
if (!SQL_SUCCEEDED(ret)) //连接失败时返回错误值
return -1;
ret = SQLConnect(serverhdbc,
"SQLServer",SQL_NTS,
"sa",SQL_NTS,
"sa",SQL_NTS);
if (!SQL_SUCCEEDED(ret)) //连接失败时返回错误值
return -1;
/* Step 4 :初始化语句句柄 */
ret = SQLAllocHandle(SQL_HANDLE_STMT, kinghdbc, &kinghstmt);
ret = SQLSetStmtAttr(kinghstmt,SQL_ATTR_ROW_BIND_TYPE,(SQLPOINTER)SQL_BIND_BY_COLUMN,SQL_IS_INTEGER );

ret = SQLAllocHandle(SQL_HANDLE_STMT, serverhdbc, &serverhstmt);
/* Step 5 :两种方式执行语句 */

/* 预编译带有参数的语句 */
ret = SQLPrepare(serverhstmt,"INSERT INTO STUDENT (SNO,SNAME,SSEX,SAGE,SDEPT) VALUES ( , , , , )", SQL_NTS);
if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO)
{
ret = SQLBindParameter(serverhstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR,SQL_CHAR, SNO_LEN, 0, sSno, 0, &cbSno);
ret = SQLBindParameter(serverhstmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR,SQL_CHAR, NAME_LEN, 0, sName, 0, &cbName);
ret = SQLBindParameter(serverhstmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR,SQL_CHAR, 2, 0, sSex, 0, &cbSex);
ret = SQLBindParameter(serverhstmt, 4, SQL_PARAM_INPUT, SQL_C_LONG,SQL_INTEGER, 0, 0, &sAge, 0, &cbAge);
ret = SQLBindParameter(serverhstmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR,SQL_CHAR, DEPART_LEN, 0, sDepart, 0, &cbDepart);
}

/*执行SQL语句*/
ret = SQLExecDirect(kinghstmt,"SELECT * FROM STUDENT",SQL_NTS);
if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO)
{
ret = SQLBindCol(kinghstmt, 1, SQL_C_CHAR,sSno,SNO_LEN, &cbSno);
ret = SQLBindCol(kinghstmt, 2, SQL_C_CHAR, sName, NAME_LEN, &cbName);
ret = SQLBindCol(kinghstmt, 3, SQL_C_CHAR, sSex, SSEX_LEN, &cbSex);
ret = SQLBindCol(kinghstmt, 4, SQL_C_LONG, &sAge, 0, &cbAge);
ret = SQLBindCol(kinghstmt, 5, SQL_C_CHAR, sDepart, DEPART_LEN, &cbDepart);

2-------------------------------------------

1.提取单条记录
//#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
//no_namespace,rename("EOF","adoEOF"),named_guids
CoInitialize(NULL);
_bstr_t varSource="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=*.mdb";
//_bstr_t varSource="Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"
_ConnectionPtr m_pConnection(_uuidof(Connection));
m_pConnection->Open(varSource,"","",adModeUnknow);
_RecordsetPtr m_pSet(_uuid(Recordset));
try {
m_pSet->Open(%%1,m_pConnection.GetInterfacePtr()
adOpenDynamic,adLockPessimistic,adCmdText);
}
catch(_com_error *e){
{
AfxMessageBox(e->ErrorMessage());
return;
}
_variant_t var;
CString %%2="";
long fldc=m_pSet->GetFields()->GetCount();
long i=0;
try {
m_pSet->MoveFirst();
if(!m_pSet->adoEOF)
{
for(i=0;i<fldc;i++)
{
var=m_pSet->GetCollect((long)i);
var.ChangeType(VT_BSTR);
%%2+=var.bstrVal;
%%2+=" ";
}
//m_pSet->MoveNext();
}
}
catch(_com_error *e){
AfxMessageBox(e->ErrorMessage());
delete e;
}
//m_pSet->MoveFirst();
CoUninitialize(NULL);

2.单值比较
//#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
//no_namespace,rename("EOF","adoEOF"),named_guids
CoInitialize(NULL);
_bstr_t varSource="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=*.mdb";
//_bstr_t varSource="Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"
_ConnectionPtr m_pConnection(_uuidof(Connection));
m_pConnection->Open(varSource,"","",adModeUnknow);
_RecordsetPtr m_pSet(_uuid(Recordset));
try {
m_pSet->Open(%%1,m_pConnection.GetInterfacePtr()
adOpenDynamic,adLockPessimistic,adCmdText);
}
catch(_com_error *e){
{
AfxMessageBox(e->ErrorMessage());
return;
}
_variant_t var;
try {
m_pSet->MoveFirst();
if(!m_pSet->adoEOF)
{
var=m_pSet->GetCollect((long)0);
var.ChangeType(VT_I2);
int %%3=var.intVal;
if(%%3==%%4)
{
%%5
}
//m_pSet->MoveNext();
}
catch(_com_error *e){
AfxMessageBox(e->ErrorMessage());
delete e;
}
//m_pSet->MoveFirst();
CoUninitialize(NULL);

3.显示表格
//#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
//no_namespace,rename("EOF","adoEOF"),named_guids
CoInitialize(NULL);
_bstr_t varSource="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=*.mdb";
//_bstr_t varSource="Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"
_ConnectionPtr m_pConnection(_uuidof(Connection));
m_pConnection->Open(varSource,"","",adModeUnknow);
//打开属性为默认(adModeRead(只读),adModeWrite(可写),adModeReadWrite(可读写)等)
_RecordsetPtr m_pSet(_uuid(Recordset));
try {
HRESULT hr=m_pSet->Open(%%1,m_pConnection.GetInterfacePtr(),
adOpenDynamic,adLockPessimistic,adCmdText);
}
catch(_com_error *e){
AfxMessageBox(e->ErrorMessage());
}
if(SUCCESSED(hr))
{
//表打开成功
}
FieldsPtr p_fields=m_pSet->Fields;
FieldPtr p_field;
_variant_t var_index;
LPCSTR field_name;
int index=0;
_bstr_t bstr_field_name;
int countfields=p_fields->GetCount();
CString *Column=new CString[countfields];
CListCtrl *pList=(CListCtrl*)GetDlgItem(%%1);//IDC_LIST_TABLEDATA
VERIFY(pList);
pList->DeleteAllItems();
for(index=0;index<countfields;index++)
{
var_index.vt=VT_I4;
var_index.IVal=index;
p_field=p_fields->Item[var_index];
bstr_field_name=p_field->GetName();
field_name=(LPCSTR)bstr_field_name;
Column[index]=field_name;
int ColumnWidth=Column[index].GetLength()*15;
pList->InsertColumn(index,field_name,LVCFMT_CENTER,ColumnWidth);
}
int i=0;
_bstr_t vCol;
//pList->SetTextBkColor(RGB(122,200,122));
//pList->SetTextColor(RGB(0,0,200));
while(!m_pSet->adoEOF)
{
pList->Insert(i,atoi(i));
for(int j=0;j<countfields;j++)
{
vCol=m_pSet->GetCollect((long)j);
pList->SetItemText(i,j,vCol);
}
m_pSet->MoveNext();
i++;
}
CoUninitialize(NULL);

3----------------------------------------------
BOOL CRoominfo::OnInitDialog()
{
CDialog::OnInitDialog();
m_roomlist.InsertColumn(0,"房间号",LVCFMT_LEFT,60);
m_roomlist.InsertColumn(1,"房间类别",LVCFMT_LEFT,78);
m_roomlist.InsertColumn(2,"房间面积",LVCFMT_LEFT,78);
m_roomlist.InsertColumn(3,"床位数",LVCFMT_LEFT,60);
m_roomlist.InsertColumn(4,"空调",LVCFMT_LEFT,45);
m_roomlist.InsertColumn(5,"地毯",LVCFMT_LEFT,45);
m_roomlist.InsertColumn(6,"电话",LVCFMT_LEFT,45);
m_roomlist.InsertColumn(7,"电视",LVCFMT_LEFT,45);
m_roomlist.InsertColumn(8,"卫生间",LVCFMT_LEFT,60);
m_roomlist.InsertColumn(9,"价格",LVCFMT_LEFT,74);
RECT rect;
m_roomlist.GetWindowRect(&rect);
m_roomlist.SetExtendedStyle(LVS_EX_FULLROWSELECT);
RefreshData();
return TRUE;
}

void CRoominfo::RefreshData()
{
if(!db.IsOpen())
{
db.OpenEx(_T("DSN=Hotel;UID=YILING"),CDatabase::noOdbcDialog);
}
m_roomlist.DeleteAllItems();
CRominfoset m_roomset(&db);
m_roomset.Open(AFX_DB_USE_DEFAULT_TYPE,"SELECT * FROM [RoomInfor]");
if(m_roomset.GetRecordCount()!=0)
m_roomset.MoveFirst();
int i=0;
while(!m_roomset.IsEOF())
{
int temp=0;
CString str;
m_roomlist.InsertItem(i,"");
str.Format("%s",m_roomset.m_RoomID);
m_roomlist.SetItemText(i,0,str);
str.Format("%s",m_roomset.m_RoomType);
m_roomlist.SetItemText(i,1,str);
str.Format("%f",m_roomset.m_Area);
m_roomlist.SetItemText(i,2,str);
str.Format("%d",m_roomset.m_Bednum);
m_roomlist.SetItemText(i,3,str);
str.Format("%s",m_roomset.m_Aircondition);
m_roomlist.SetItemText(i,4,str);
str.Format("%s",m_roomset.m_Carpet);
m_roomlist.SetItemText(i,5,str);
str.Format("%s",m_roomset.m_Telephone);
m_roomlist.SetItemText(i,6,str);
str.Format("%s",m_roomset.m_Television);
m_roomlist.SetItemText(i,7,str);
str.Format("%s",m_roomset.m_Toilet);
m_roomlist.SetItemText(i,8,str);
str.Format("%s",m_roomset.m_Price);
m_roomlist.SetItemText(i,9,str);
m_roomset.MoveNext();
i++;
}
m_roomset.Close();
db.Close();
}

BEGIN_MESSAGE_MAP(CRoominfo, CDialog)
//{{AFX_MSG_MAP(CRoominfo)
ON_BN_CLICKED(IDC_ADDROOM, OnAddroom)
ON_BN_CLICKED(IDC_DELROOM, OnDelroom)
ON_BN_CLICKED(IDCHANGE, OnChange)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRoominfo message handlers

void CRoominfo::OnAddroom()
{
// TODO: Add your control notification handler code here
CAddroom addroom;
if(addroom.DoModal()==IDOK)
{
CString sql;
CAddroomset m_user;
if(!db.IsOpen())
{
db.OpenEx(_T("DSN=Hotel;UID=YILING"),CDatabase::noOdbcDialog);
}
m_user.Open(AFX_DB_USE_DEFAULT_TYPE,"SELECT * FROM [RoomInfor]");
sql.Format("insert into [RoomInfor] values(\'%s\',\'%s\',%f,%d,\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',%f)",addroom.m_roomid,addroom.m_roomtype,addroom.m_area,addroom.m_bednum,addroom.m_air,addroom.m_carpet,addroom.m_tel,addroom.m_tv,addroom.m_wc,addroom.m_price);
db.ExecuteSQL(sql);
db.Close();
RefreshData();
}
}

void CRoominfo::OnDelroom()
{
// TODO: Add your control notification handler code here
int i;
CString str;
CRominfoset m_user;
i=m_roomlist.GetSelectionMark();
str=m_roomlist.GetItemText(i,0);
m_user.Open(AFX_DB_USE_DEFAULT_TYPE,"SELECT * FROM [RoomInfor] WHERE [RoomID]='"+str+"'");
m_user.Delete();
m_user.Close();
RefreshData();

}

void CRoominfo::OnChange()
{
// TODO: Add your control notification handler code here
int i;
CString str;
i=m_roomlist.GetSelectionMark();
str=m_roomlist.GetItemText(i,0);
CModroominfo dlg;
if(dlg.DoModal()==IDOK)
{
CString strsql;
db.OpenEx(_T("DSN=Hotel;UID=YILING"),CDatabase::noOdbcDialog);
strsql.Format("update [RoomInfor] set [RoomID]='%s',[RoomType]='%s',[Area]='%f',[Bednum]='%d',[Aircondition]='%s',[Carpet]='%s',[Telephone]='%s',[Television]='%s',[Toilet]='%s',[Price]='%f' where [RoomID]='%s'",dlg.m_id,dlg.m_type,dlg.m_area,dlg.m_bednum,dlg.m_air,dlg.m_carpet,dlg.m_tel,dlg.m_tv,dlg.m_wc,dlg.m_price,str);
db.ExecuteSQL(strsql);
db.Close();
}
RefreshData();

}

求问C++怎么连接SQL server啊
这里需要根据自己PC的数据库的情况 *\/ pMyConnect->Open("Provider=SQLOLEDB; Server=.;Database=AIS2; uid=sa;

C语言怎样连接SQLserver?
1、安装本机环境:这里以sql2008r2+vs2010为例。先在本机安装sql2008r2,再安装vs2010。安装完成以后可以进去我的电脑-管理-服务找到sqlserver服务是否安装成功并启动。2、配置本机数据连接:(1)点击电脑左下角的开始-控制面板-管理工具-数据源(ODBC)。(2)双击打开,点击用户DNS菜单,点击新增,弹...

VC++将时间插入SQL server数据库
然后用定时器定时插入。。点击按钮kill掉定时器

...对话框 ,然后怎样通过SQL Server 连接到数据库?
\/\/打开数据库链接 int DBConnection::OpenConnect(void){ try { \/\/创建连接对象 m_pConnection.CreateInstance("ADODB.Connection");\/\/设置连接字符串 _bstr_t strConnect ="Provider=SQLOLEDB;Data Source=20110121-1545\\\\SQLEXPRESS;\\ Initial Catalog=ExpManDB;User ID=sa;PWD=123";\/\/设置连接超时...

如何用VC++将字符串存储到sql server中???
ADO方法 在保存消息处理函数中加入以下代码。当然还有导入ado数据库,初始化Com环境。先看代码,不会再Call 我 _Connection pConection;_Recordset pRecordset;\/\/连接Sql sever数据库 pConection.CreateInstance(_uuidof(Conection));CString strConnect;\/\/连接字符串 strConnect="获取连接字符串";pConnection-...

c语言用vc连接sql server 2000怎么连,具体代码?
1.提取单条记录 \/\/#import "C:\\Program Files\\Common Files\\System\\ADO\\msado15.dll" \\ \/\/no_namespace,rename("EOF","adoEOF"),named_guids CoInitialize(NULL);_bstr_t varSource="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=*.mdb";\/\/_bstr_t varSource="Data Source=myServer...

Vc++6.0 和 sql server 2000做的人事工资管理系统 登陆是出现 sa用户...
具体的方法是: 1:打开SQL Server Manager管理器!在左面找到 ‘安全性’ 单击右键 选择‘新建”,“登录” 弹出一个对话框,在登录名中输入你的登录号,选择'SQLSERVER身份验证',并输入密码,可以把‘用户下次登录时必须修改密码’取消掉。 点击‘用户映射’,在右面选择要映射的数据库,并在前面...

vc++连接sql 数据库失败 未指定的错误求教。。。
TreeConnString.Format("driver={SQL Server}; Server=%s; DATABASE=%s; UID=%s; PWD=%s", 数据库所在服务器ip, 数据库名, 用户名, 密码);

试述嵌入式SQL语言使用要考虑
(3)初始化SQL Server的预编译环境。在命令行方式下运行文件:\\Devtools\\samples\\esqlc\\setenv.bat。( 4) VC++6.0环境配置。具体配置分为如下三步[:①Tools->options->directories->Include Files:添加 C:\\Program Files\\Microsoft SQL Server\\devtools\\include。将SQL server自带的用于数据库开发的头...

SQL数据库安装后如何与应用程序进行数据交换?
举个用MFC建一个操作数据库的例子 你用SQL server建好数据库后,然后添加数据源(比喻用ODBC注册数据源,控制面板\\所有控制面板项\\管理工具里面添加),在用vc++6.0的mfc appliwizard 建一个基于数据库支持的单文档工程,通过添加成员变量来关联数据库里面的属性。。。还有许多方法,具体你还要找本基于...

相似回答
大家正在搜