當前位置:首頁 » 操作系統 » c連接資料庫的方式

c連接資料庫的方式

發布時間: 2023-04-04 07:34:40

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)

2. c/c++寫伺服器一般用什麼方式訪問資料庫的

要做伺服器端的話資料庫就是放在你的伺服器上的, 資料庫會提供相應的訪問介面, 具體使用方式可以搜一下"C++連接資料庫"之類的
http是客戶端訪問伺服器才用得到, 直接操作資料庫的總是伺服器端而不是客戶端

3. c語言怎麼連接mysql資料庫 代碼

//vc工具中添加E:\WAMP\BIN\MYSQL\MYSQL5.5.8\LIB 路徑
//在工程設置-》鏈接》庫模塊中添加 libmysql.lib
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <winsock.h>
#include "E:\wamp\bin\mysql\mysql5.5.8\include\mysql.h"
void main(){
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server ="localhost";
char *user ="root";
char *password="";
char *database="test";
char sql[1024]="select * from chinaren";
conn=mysql_init(NULL);
if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0)){
fprintf(stderr,"%s\n",mysql_error(conn));
exit(1);
}
if(mysql_query(conn,sql)){
fprintf(stderr,"%s\n",mysql_error(conn));
exit(1);
}
res=mysql_use_result(conn);
while((row = mysql_fetch_row(res))!=NULL){
printf("%s\n",row[2]);
}
mysql_free_result(res);
mysql_close(conn);
}
===============================
#if defined(_WIN32) || defined(_WIN64) //為了支持windows平台上的編譯
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include "mysql.h"
//定義資料庫操作的宏,也可以不定義留著後面直接寫進代碼
#define SELECT_QUERY "show tables;"
int main(int argc, char **argv) //char **argv 相當於 char *argv[]
{
MYSQL mysql,*handle; //定義資料庫連接的句柄,它被用於幾乎所有的MySQL函數
MYSQL_RES *result; //查詢結果集,結構類型
MYSQL_FIELD *field ; //包含欄位信息的結構
MYSQL_ROW row ; //存放一行查詢結果的字元串數組
char querysql[160]; //存放查詢sql語句字元串
//初始化
mysql_init(&mysql);
//連接資料庫
if (!(handle = mysql_real_connect(&mysql,"localhost","user","pwd","dbname",0,NULL,0))) {
fprintf(stderr,"Couldn't connect to engine!\n%s\n\n",mysql_error(&mysql));
}
sprintf(querysql,SELECT_QUERY,atoi(argv[1]));
//查詢資料庫
if(mysql_query(handle,querysql)) {
fprintf(stderr,"Query failed (%s)\n",mysql_error(handle));
}
//存儲結果集
if (!(result=mysql_store_result(handle))) {
fprintf(stderr,"Couldn't get result from %s\n", mysql_error(handle));
}
printf("number of fields returned: %d\n",mysql_num_fields(result));
//讀取結果集的內容
while (row = mysql_fetch_row(result)) {
printf("table: %s\n",(((row[0]==NULL)&&(!strlen(row[0]))) ? "NULL" : row[0]) ) ;
}
//釋放結果集
mysql_free_result(result);
//關閉資料庫連接
mysql_close(handle);
system("PAUSE");
//為了兼容大部分的編譯器加入此行
return 0;
}

4. c程序通過什麼連接oracle

一般C語言連接oracle資料庫通過使用oracle提供的OCI介面和PROC編程介面兩種方式。
OCI方式純粹是一些函數介面。
PROC是oracle提供的一種C與ORACLE
SQL的混合編程。程序(以.pc為後綴)編好之後,使用oracle提供的proc預編譯程序,將pc文件編譯成c文件(這一過程,相當於將SQL轉換為OCI的介面),然後再使用c語言編譯器生成可以執行文件。
OCI方式不容易入門,它擁有大量的介面函數,要很快熟悉它,非常難。但OCI方式的編程效率很高。
porc方式簡單易用。可用於對性能要求不太高的項目。

5. 跪求Visual C++程序連接資料庫的方法,十分火急!!!

C#的各種連接資料庫2007年11月01日 星期四 11:461.C#連接連接Access
程序代碼:
-------------------------------------------------------------------------------
using System.Data;
using System.Data.OleDb;

......

string strConnection="Provider=Microsoft.Jet.OleDb.4.0;";
strConnection+=@"Data Source=C:\BegASPNET\Northwind.mdb";

OleDbConnection objConnection=new OleDbConnection(strConnection);

......

objConnection.Open();
objConnection.Close();

......

--------------------------------------------------------------------------------

解釋:

連接Access資料庫需要導入額外的命名空間,所以有了最前面的兩條using命令,這是必不可少的!

strConnection這個變數里存放的是連接資料庫所需要的連接字元串,他指定了要使用的數據提供者和要使用的數據源.

"Provider=Microsoft.Jet.OleDb.4.0;"是指數據提供者,這里使用的是Microsoft Jet引擎,也就是Access中的數據引擎,asp.net就是靠這個和Access的資料庫連接的.

"Data Source=C:\BegASPNET\Northwind.mdb"是指明數據源的位置,他的標准形式是"Data Source=MyDrive:MyPath\MyFile.MDB".

PS:
1."+="後面的"@"符號是防止將後面字元串中的"\"解析為轉義字元.
2.如果要連接的資料庫文件和當前文件在同一個目錄下,還可以使用如下的方法連接:
strConnection+="Data Source=";
strConnection+=MapPath("Northwind.mdb");
這樣就可以省得你寫一大堆東西了!
3.要注意連接字元串中的參數之間要用分號來分隔.

"OleDbConnection objConnection=new OleDbConnection(strConnection);"這一句是利用定義好的連接字元串來建立了一個鏈接對象,以後對資料庫的操作我們都要和這個對象打交道.

"objConnection.Open();"這用來打開連接.至此,與Access資料庫的連接完成.
--------------------------------------------------------------------------------

2.C#連接SQL Server
程序代碼:
--------------------------------------------------------------------------------

using System.Data;
using System.Data.SqlClient;

...

string strConnection="user id=sa;password=;";
strConnection+="initial catalog=Northwind;Server=YourSQLServer;";
strConnection+="Connect Timeout=30";

SqlConnection objConnection=new SqlConnection(strConnection);

...

objConnection.Open();
objConnection.Close();

...

--------------------------------------------------------------------------------

解釋:

連接SQL Server資料庫的機制與連接Access的機制沒有什麼太大的區別,只是改變了Connection對象和連接字元串中的不同參數.

首先,連接SQL Server使用的命名空間不是"System.Data.OleDb",而是"System.Data.SqlClient".

其次就是他的連接字元串了,我們一個一個參數來介紹(注意:參數間用分號分隔):
"user id=sa":連接資料庫的驗證用戶名為sa.他還有一個別名"uid",所以這句我們還可以寫成"uid=sa".
"password=":連接資料庫的驗證密碼為空.他的別名為"pwd",所以我們可以寫為"pwd=".
這里注意,你的SQL Server必須已經設置了需要用戶名和密碼來登錄,否則不能用這樣的方式來登錄.如果你的SQL Server設置為Windows登錄,那麼在這里就不需要使用"user id"和"password"這樣的方式來登錄,而需要使用"Trusted_Connection=SSPI"來進行登錄.
"initial catalog=Northwind":使用的數據源為"Northwind"這個資料庫.他的別名為"Database",本句可以寫成"Database=Northwind".
"Server=YourSQLServer":使用名為"YourSQLServer"的伺服器.他的別名為"Data Source","Address","Addr".如果使用的是本地資料庫且定義了實例名,則可以寫為"Server=(local)\實例名";如果是遠程伺服器,則將"(local)"替換為遠程伺服器的名稱或IP地址.
"Connect Timeout=30":連接超時時間為30秒.

在這里,建立連接對象用的構造函數為:SqlConnection.
--------------------------------------------------------------------------------

3.C#連接Oracle
程序代碼:
--------------------------------------------------------------------------------

using System.Data.OracleClient;
using System.Data;

//在窗體上添加一個按鈕,叫Button1,雙擊Button1,輸入以下代碼
private void Button1_Click(object sender, System.EventArgs e)
{
string ConnectionString="Data Source=sky;user=system;password=manager;";//寫連接串
OracleConnection conn=new OracleConnection(ConnectionString);//創建一個新連接
try
{
conn.Open();
OracleCommand cmd=conn.CreateCommand();

cmd.CommandText="select * from MyTable";//在這兒寫sql語句
OracleDataReader odr=cmd.ExecuteReader();//創建一個OracleDateReader對象
while(odr.Read())//讀取數據,如果odr.Read()返回為false的話,就說明到記錄集的尾部了
{
Response.Write(odr.GetOracleString(1).ToString());//輸出欄位1,這個數是欄位索引,具體怎麼使用欄位名還有待研究
}
odr.Close();
}
catch(Exception ee)
{
Response.Write(ee.Message); //如果有錯誤,輸出錯誤信息
}
finally
{
conn.Close(); //關閉連接
}
}

--------------------------------------------------------------------------------

4.C#連接MySQL
程序代碼:
--------------------------------------------------------------------------------

using MySQLDriverCS;

// 建立資料庫連接
MySQLConnection DBConn;
DBConn = new MySQLConnection(new MySQLConnectionString("localhost","mysql","root","",3306).AsString);
DBConn.Open();

// 執行查詢語句
MySQLCommand DBComm;
DBComm = new MySQLCommand("select Host,User from user",DBConn);

// 讀取數據
MySQLDataReader DBReader = DBComm.ExecuteReaderEx();

// 顯示數據
try
{
while (DBReader.Read())
{
Console.WriteLine("Host = {0} and User = {1}", DBReader.GetString(0),DBReader.GetString(1));
}
}
finally
{
DBReader.Close();
DBConn.Close();
}

//關閉資料庫連接
DBConn.Close();

--------------------------------------------------------------------------------

5.C#連接IBM DB2
程序代碼:
--------------------------------------------------------------------------------

OleDbConnection1.Open();
//打開資料庫連接
OleDbDataAdapter1.Fill(dataSet1,"Address");
//將得來的數據填入dataSet
DataGrid1.DataBind();
//綁定數據
OleDbConnection1.Close();
//關閉連接

//增加資料庫數據
在Web Form上新增對應欄位數量個數的TextBox,及一個button,為該按鍵增加Click響應事件代碼如下:

this.OleDbInsertCommand1.CommandText = "INSERTsintosADDRESS(NAME,
EMAIL, AGE, ADDRESS) valueS
(''"+TextBox1.Text+"'',''"+TextBox2.Text+"'',''"+TextBox3.Text+"'',''"+TextBox4.Text+"'')";
OleDbInsertCommand1.Connection.Open();
//打開連接
OleDbInsertCommand1.ExecuteNonQuery();
//執行該SQL語句
OleDbInsertCommand1.Connection.Close();
//關閉連接

--------------------------------------------------------------------------------

6.C#連接SyBase
程序代碼: (OleDb)
--------------------------------------------------------------------------------

Provider=Sybase.ASEOLEDBProvider.2;Initial Catalog=資料庫名;User ID=用戶名;Data Source=數據源;Extended Properties="";Server Name=ip地址;Network Protocol=Winsock;Server Port Address=5000;

Visual C 連接資料庫

- 連接SQL Server 2000
使用DAO
看下面的代碼:
CDaoDatabase db;

CString conn;

conn="ODBC;Driver=

SQLServer};Server=192.168.0.4;Database=mydb;uid=sa;pwd=";

db.Open(NULL,FALSE,FALSE,conn);

CString s=db.GetConnect();

CDaoRecordset rs(&db);

rs.Open(AFX_DAO_USE_DEFAULT_TYPE,"select * from tb_code");

TRACE("%drn",rs.GetRecordCount());

rs.Close();

db.Close();
其中Server=192.168.0.4是sql server伺服器的ip地址,也可以用主機名表示;Database=mydb表示使用mydb資料庫;uid和pwd分別表示訪問資料庫的用戶名和密碼。
注意:上面的代碼的運行還要用#include "afx.h" 把afx.h包含進來。當然最好還是加入些必要的出錯處理代碼,這里就不在詳述了。

二 連接 Microsoft Access資料庫
看下面實例的代碼,這也是我用的比較多的一種方法,access文件只要放在和應用程序相同的文件夾中就能保證代碼可以正確執行。
CString sPath,message;
GetMoleFileName(NULL,sPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH);
sPath.ReleaseBuffer();
int nPos;
nPos=sPath.ReverseFind('');
sPath=sPath.Left(nPos);
CString runpath=sPath+"clzmf.mdb"; //這里的clzmf.mdb就是要打開的資料庫名
runpath.Replace('','/');
m_pDatabase=new CDaoDatabase;
try
{
m_pDatabase->Open(runpath);
}
catch(CDaoException *e)
{
message=_T("Could't open database-- Exception:");
message+=e->m_pErrorInfo->m_strDescription;
AfxMessageBox(message);
}

CString sqlstr="select * from user_info where user_id='myid';
CDaoRecordset rs(m_pDatabase);
try
{
rs.Open(AFX_DAO_USE_DEFAULT_TYPE,sqlstr);
}
catch(CDaoException *e)
{
message=_T("Could't open Recordset-- Exception:");
message+=e->m_pErrorInfo->m_strDescription;
AfxMessageBox(message);
}
這里加入了異常處理的代碼,其他注意選項可以參照Sql Server 2000的注意選項。

#連接SQL資料庫並且在表中進行對數據操作2007-11-30 16:07using System;
using System.Collections.Generic;
using System.Text;
using Model;
using System.Data;
using System.Data.SqlClient;

//在表中修改

private void btnOK_Click(object sender, EventArgs e)
{
try
{
DialogResult result = MessageBox.Show("你確定?", "系統提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{

//string strConn = "server=.;uid=sa;pwd=;database=wareDB";
string strConn = "server=.;uid=sa;pwd=;database=ShopManegerDB";
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from Shop";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd; //獲取選擇命令
//創建自動生成Sql對象
SqlCommandBuilder builder = new SqlCommandBuilder(da);

//保存修改

da.Update(ds.Tables[0]); //提交更新
MessageBox.Show("修改成功");
this.Isindsplay();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}

//在表中操作刪除

private void 刪除ToolStripMenuItem_Click(object sender, EventArgs e)
{
//保證選中
if (dgvData.CurrentCell.RowIndex != -1)
{
DialogResult result = MessageBox.Show("你確定?", "系統提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
//刪除
ds.Tables[0].Rows[dgvData.CurrentCell.RowIndex].Delete(); //刪除該選中行
}
}

}

刪除成功後,在次按保存按鈕.

6. 用C語言怎麼實現與資料庫的連接

#include<mysql/mysql.h>

#include<stdio.h>

intmain()

{

MYSQL*conn;

MYSQL_RES*res;

MYSQL_ROWrow;

char*server="localhost";//本地連接

char*user="root";//

char*password="525215980";//mysql密碼

char*database="student";//資料庫名

char*query="select*fromclass";//需要查詢的語句

intt,r;

conn=mysql_init(NULL);

if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0))

{

printf("Errorconnectingtodatabase:%s ",mysql_error(conn));

}else{

printf("Connected... ");

}

t=mysql_query(conn,query);

if(t)

{

printf("Errormakingquery:%s ",mysql_error(conn));

}else{

printf("Querymade... ");

res=mysql_use_result(conn);

if(res)

{

while((row=mysql_fetch_row(res))!=NULL)

{

//printf("num=%d ",mysql_num_fields(res));//列數

for(t=0;t<mysql_num_fields(res);t++)

printf("%8s",row[t]);

printf(" ");

}

}

mysql_free_result(res);

}

mysql_close(conn);

return0;

}

(6)c連接資料庫的方式擴展閱讀

C語言使用注意事項:

1、指針是c語言的靈魂,一定要靈活的使用它:

(1)、指針的聲明,創建,賦值,銷毀等

(2)、指針的類型轉換,傳參,回調等

2、遞歸調用也會經常用到:

(1)、遞歸遍歷樹結構

(2)、遞歸搜索

7. c程序通過什麼連接oracle

一般C語言連接oracle資料庫通過使用oracle提供的OCI介面和PROC編程介面兩種方式。
OCI方式純粹是一些函數介面。
PROC是oracle提供的一種C與ORACLE SQL的混合編程。程序(以.pc為後綴)編好之後,使用oracle提供的proc預編譯程序,將pc文件編譯成c文件(這一過程,相當於將SQL轉換為OCI的介面),然後再使用c語言編譯器生成可以執行文件。
OCI方式不容易入門,它擁有大量的介面函數,要很快熟悉它,非常難。但OCI方式的編程效率很高。
porc方式簡單易用。可用於對性能要求不太高的項目。

8. c或c++連接資料庫,求代碼,求指教,很急!

對於SQL Server資料庫,
C++使用MFC庫,主要有兩種方法可以連接sql資料庫
1.利用ADO連接:
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
//必須import這個dll,這個文件通常放在C:\Program Files\Common Files\System\ado路徑下.
_ConnectionPtr m_ptrConnection; //資料庫連接對象
構造函數中添加如下語句
m_ptrConnection = NULL;
::CoInitialize(NULL);
//連接資料庫的主要代碼
BOOL DataVisitor::ConnectDataBase(_bstr_t connectionStr)
{
/*
Added by stone. If IDOConnection has not been set up,then create one.
*/
if(m_ptrConnection == NULL)
{
HRESULT hr = m_ptrConnection.CreateInstance(__uuidof(Connection));
if (FAILED(hr))
{
return FALSE;
}
else
{
_bstr_t strConnect = connectionStr;
//"Provider=SQLOLEDB;Server=(local);Database=navigation; uid=sa; pwd=3277625;";

m_ptrConnection->CursorLocation = adUseClient;
m_ptrConnection->IsolationLevel = adXactReadCommitted;
try
{
m_ptrConnection->Open(strConnect,"","",adModeUnknown);
return TRUE;
}
catch (_com_error e)
{
// AfxMessageBox((char *)e.Description());
return FALSE;
}

}
}
return TRUE;
}

2. 利用ODBC連接
#include <afx.h>
CDaoDatabase *MyDataBase;

BOOL MyDB_OperSqL::Open_MyDatabase(CString connstr)
{
try
{
if (MyDataBase == NULL)
{
MyDataBase = new CDaoDatabase();
}
MyDataBase->Open(NULL,0,0,connstr);

}
catch( CDaoException* e )
{
CString message = _T("MyDB_OperSqL 資料庫異常: ");
message += e->m_pErrorInfo->m_strDescription;
char info[400];
sprintf(info,message);
DispErrorMessage(info,__LINE__);
e->Delete( );
return FALSE;
}
catch (CMemoryException *e)
{
DispErrorMessage("MyDB_OperSqL 內存異常!",__LINE__);
e->Delete( );
return FALSE;
}
catch(...)
{
DispErrorMessage("MyDB_OperSqL 其它異常!",__LINE__);
return FALSE;
}
return TRUE;
}
這里的連接字元串connstr一般是如下內容
"ODBC;DRIVER={SQL Server};SERVER=(local);DATABASE=yourDataBase;UID=yourID;PWD=yourPassword"

如果直接用Microsoft ADO Datebase Control控制項的話,連接字串可以自己生成,在控制項的屬性裡面找到拷貝就行,這種最簡單

9. C++如何連接資料庫 用什麼方式最好

1、在stdafx.h文件最後(即#endif // _AFX_NO_AFXCMN_SUPPORT下面)添加:
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")

2、初始化COM:
AfxOleInit();//這行代碼要放在功能執行前,如果是基於對話框建立的程序,那就放在第一個對話框類的OnInitDialog()函數的return TRUE;前

3、在用到資料庫的地方:
_ConnectionPtr m_pConnection;///聲明資料庫連接變數
_RecordsetPtr m_pRecordset;///聲明資料庫集合變數
CString strCn;
strCn.Empty();

(1)連接資料庫
HRESULT hr;
try
{
_variant_t RecordsAffected;
hr = m_pConnection.CreateInstance("ADODB.Connection");///創建Connection對象
if(SUCCEEDED(hr))
{
hr = m_pConnection->Open("DSN=test;UID=;PWD=;","","",adModeUnknown);///連接資料庫
}
}
catch( _com_error e)///捕捉異常
{
CString errormessage;
errormessage.Format("連接資料庫失敗!\r\n錯誤信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);///顯示錯誤信息
}

(2)通過SQL讀數據
CString sql;
try
{
m_pRecordset.CreateInstance("ADODB.Recordset");
m_pRecordset->Open((_variant_t)sql,_variant_t((IDispatch*)m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
}
catch(_com_error e)///捕捉異常
{
CString errorMessage = e.ErrorMessage();
AfxMessageBox("讀取數據時出錯:"+sql+errorMessage);///顯示錯誤信息
}

(3)通過sql語句添加、修改、刪除記錄
_variant_t RecordsAffected;

try
{
m_pConnection->Execute((_bstr_t)Sql,&RecordsAffected,adCmdText);
}
catch(_com_error *e)
{
AfxMessageBox(e->ErrorMessage());
}

10. c如何與sql資料庫連接

用odbc或db-libary給你一小段db-library程序
int CreateProc(PDBPROCESS * dbproc,char * pwd,char * sname)
{
PLOGINREC login;
// char sname[20];
unsigned short num;

// memset(sname,0,sizeof(sname));
login=dblogin();
DBSETLUSER(login,"sa");
if(strlen(pwd)>0)
{
DBSETLPWD(login,pwd);
}

DBSETLVERSION(login, DBVER60);
dbprocerrhandle(login,err_handler);
dbprocmsghandle(login,msg_handler);
// dbserverenum(LOC_SEARCH,sname,sizeof(sname),&num);
DBSETLTIME(login,20);
*dbproc=dbopen(login,sname);
if(*dbproc == NULL){

return ERR;
}

dbuse(*dbproc,"ccenter");
dbfreelogin(login);
return OK;
}

int check_grp_no(int grp_no, unsigned int * small_len)
{
int res=0;
int cnt=0;
dbcancel(dbproc);
dbfcmd(dbproc," select small_len from grp_table where grp_no=%d",grp_no);
res=dbsqlexec(dbproc);

if((res=dbresults(dbproc))==SUCCEED){
dbbind(dbproc,1,INTBIND,0,(unsigned char *)small_len);
while(dbnextrow(dbproc)!=NO_MORE_ROWS){
cnt++;
return OK;
}

}

return ERR;
}

熱點內容
內置存儲卡可以拆嗎 發布:2025-05-18 04:16:35 瀏覽:336
編譯原理課時設置 發布:2025-05-18 04:13:28 瀏覽:378
linux中進入ip地址伺服器 發布:2025-05-18 04:11:21 瀏覽:612
java用什麼軟體寫 發布:2025-05-18 03:56:19 瀏覽:32
linux配置vim編譯c 發布:2025-05-18 03:55:07 瀏覽:107
砸百鬼腳本 發布:2025-05-18 03:53:34 瀏覽:944
安卓手機如何拍視頻和蘋果一樣 發布:2025-05-18 03:40:47 瀏覽:742
為什麼安卓手機連不上蘋果7熱點 發布:2025-05-18 03:40:13 瀏覽:803
網卡訪問 發布:2025-05-18 03:35:04 瀏覽:511
接收和發送伺服器地址 發布:2025-05-18 03:33:48 瀏覽:372