當前位置:首頁 » 數據倉庫 » c連接資料庫語句
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

c連接資料庫語句

發布時間: 2023-02-27 22:27:22

Ⅰ 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語言怎麼連接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;
}

Ⅲ 怎麼在linux環境下通過c/c++語言連接oracle資料庫

推薦你使用pc語言,用這個編寫代碼很容易對資料庫oracle進行操作.各種操作都非常簡單.
例如:
EXEC SQL CONNECT :UserName IDENTIFIED BY :PassWord using :ServerName;
這樣一個簡單語句就可以實現連接資料庫.
EXEC SQL CALL insert_data_sms(:spnumber,:usernumber,:content,:flag,:priority,:spnode,:sequenid_sp,:iresult);
EXEC SQL COMMIT;/*提交事務*/
可調用存儲過程.
你可以找找這方便的書看看

Ⅳ c# 區域網連接ACCESS資料庫如何寫連接字元串

1.首先使用Access創建一個數據保存在硬碟某處,使用.MDB。

Ⅳ 如何用C++連接SQL資料庫

(樓上兩位說的很對,我給你粘一篇文章吧 初學者 看看有好處。
需要的話 你可以留下郵箱 我這有一些初學者的文檔可以發給你很不錯,希望繼續努力。面試,到時候一切都是是浮雲。。。哈哈)

基本流程
萬事開頭難,任何一種新技術對於初學者來說最重要的還是「入門」,掌握其要點。讓我們來看看ADO資料庫開發的基本流程吧!
(1)初始化COM庫,引入ADO庫定義文件
(2)用Connection對象連接資料庫
(3)利用建立好的連接,通過Connection、Command對象執行SQL命令,或利用Recordset對象取得結果記錄集進行查詢、處理。
(4)使用完畢後關閉連接釋放對象。

准備工作:
為了大家都能測試本文提供的例子,我們採用Access資料庫,您也可以直接在我們提供的示例代碼中找到這個test.mdb。
下面我們將詳細介紹上述步驟並給出相關代碼。
【1】COM庫的初始化
我們可以使用AfxOleInit()來初始化COM庫,這項工作通常在CWinApp::InitInstance()的重載函數中完成,請看如下代碼:

BOOL CADOTest1App::InitInstance()
{
AfxOleInit();
......

【2】用#import指令引入ADO類型庫
我們在stdafx.h中加入如下語句:(stdafx.h這個文件哪裡可以找到?你可以在FileView中的Header Files里找到)

#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
這一語句有何作用呢?其最終作用同我們熟悉的#include類似,編譯的時候系統會為我們生成msado15.tlh,ado15.tli兩個C++頭文件來定義ADO庫。

幾點說明:
(1) 您的環境中msado15.dll不一定在這個目錄下,請按實際情況修改
(2) 在編譯的時候肯能會出現如下警告,對此微軟在MSDN中作了說明,並建議我們不要理會這個警告。
msado15.tlh(405) : warning C4146: unary minus operator applied to unsigned type, result still unsigned

【3】創建Connection對象並連接資料庫
首先我們需要添加一個指向Connection對象的指針:
_ConnectionPtr m_pConnection;
下面的代碼演示了如何創建Connection對象實例及如何連接資料庫並進行異常捕捉。

BOOL CADOTest1Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
HRESULT hr;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");///創建Connection對象
if(SUCCEEDED(hr))
{
hr = m_pConnection- >Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb","","",adModeUnknown);///連接資料庫
///上面一句中連接字串中的Provider是針對ACCESS2000環境的,對於ACCESS97,需要改為:Provider=Microsoft.Jet.OLEDB.3.51;
}
}
catch(_com_error e)///捕捉異常
{
CString errormessage;
errormessage.Format("連接資料庫失敗!\r\n錯誤信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);///顯示錯誤信息
}

在這段代碼中我們是通過Connection對象的Open方法來進行連接資料庫的,下面是該方法的原型
HRESULT Connection15::Open ( _bstr_t ConnectionString, _bstr_t UserID, _bstr_t Password, long Options )
ConnectionString為連接字串,UserID是用戶名, Password是登陸密碼,Options是連接選項,用於指定Connection對象對數據的更新許可權,
Options可以是如下幾個常量:
adModeUnknown:預設。當前的許可權未設置
adModeRead:只讀
adModeWrite:只寫
adModeReadWrite:可以讀寫
adModeShareDenyRead:阻止其它Connection對象以讀許可權打開連接
adModeShareDenyWrite:阻止其它Connection對象以寫許可權打開連接
adModeShareExclusive:阻止其它Connection對象以讀寫許可權打開連接
adModeShareDenyNone:阻止其它Connection對象以任何許可權打開連接

我們給出一些常用的連接方式供大家參考:
(1)通過JET資料庫引擎對ACCESS2000資料庫的連接

m_pConnection- >Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\test.mdb","","",adModeUnknown);

(2)通過DSN數據源對任何支持ODBC的資料庫進行連接:

m_pConnection- >Open("Data Source=adotest;UID=sa;PWD=;","","",adModeUnknown);

(3)不通過DSN對SQL SERVER資料庫進行連接:
m_pConnection- >Open("driver={SQL Server};Server=127.0.0.1;DATABASE=vckbase;UID=sa;PWD=139","","",adModeUnknown);

其中Server是SQL伺服器的名稱,DATABASE是庫的名稱

Connection對象除Open方法外還有許多方法,我們先介紹Connection對象中兩個有用的屬性ConnectionTimeOut與State
ConnectionTimeOut用來設置連接的超時時間,需要在Open之前調用,例如:
m_pConnection- >ConnectionTimeout = 5;///設置超時時間為5秒
m_pConnection- >Open("Data Source=adotest;","","",adModeUnknown);

State屬性指明當前Connection對象的狀態,0表示關閉,1表示已經打開,我們可以通過讀取這個屬性來作相應的處理,例如:

if(m_pConnection- >State)
m_pConnection- >Close(); ///如果已經打開了連接則關閉它

------------------------------------------------------------------------------------
呵呵,是啊,我以前不做VC的,所以這次老闆有個項目要做,沒辦法啊!!以後多請教啊!!
------------------------------------------------------------------------------------
你現在不少基礎的不會,上來就連接資料庫有點難
------------------------------------------------------------------------------------
要是你用vc6,就右健點擊要添加變數的控制項,選擇classwizard,選擇member variables選項卡,它會自動指到你想要添加變數的控制項,你直接點選擇add variable,起個名字就可以了
------------------------------------------------------------------------------------
我關鍵是不知道怎麼給控制項添加與之相對應的變數!!請明示啊!!
------------------------------------------------------------------------------------
CBaseEditBox是什麼東西?你不要這樣定義。應該先把控制項放在對話框窗體上,再給這個控制項添加與之相對應的變數,這樣,VC就自動把控制項和變數聯系起來了
------------------------------------------------------------------------------------
剛弄,不怎麼會,請明示!!!

我想把從資料庫中讀出來的記錄放在一個文本框中!

然後在界面上放置了一個edit box

我在類C***Dlg中添加了變數
public:
CBaseEditBox m_list

接下來我在一個按鈕的onOK事件里連接資料庫並想把得到的記錄放到m_list里

// 讀入庫中各欄位並加入列表框中
while(!m_pRecordset- >adoEOF)
{
var = m_pRecordset- >GetCollect("UserName");
if(var.vt != VT_NULL)
strName = (LPCSTR)_bstr_t(var);
var = m_pRecordset- >GetCollect("Password");
if(var.vt != VT_NULL)
strAge = (LPCSTR)_bstr_t(var);

m_list.AddString( strName + " -- > "+strAge );

m_pRecordset- >MoveNext();
}

// 默認列表指向第一項,同時移動記錄指針並顯示
m_list.SetCurSel(0);

然後一大堆錯誤:
d:\microsoft visual studio\myprojects\testado\testadodlg.h(18) : error C2146: syntax error : missing "; " before identifier "m_list "
d:\microsoft visual studio\myprojects\testado\testadodlg.h(18) : error C2501: "CBaseEditBox " : missing storage-class or type specifiers
d:\microsoft visual studio\myprojects\testado\testadodlg.h(18) : error C2501: "m_list " : missing storage-class or type specifiers
TestADODlg.cpp
d:\microsoft visual studio\myprojects\testado\testadodlg.h(18) : error C2146: syntax error : missing "; " before identifier "m_list "
d:\microsoft visual studio\myprojects\testado\testadodlg.h(18) : error C2501: "CBaseEditBox " : missing storage-class or type specifiers
d:\microsoft visual studio\myprojects\testado\testadodlg.h(18) : error C2501: "m_list " : missing storage-class or type specifiers
D:\Microsoft Visual Studio\MyProjects\TestADO\TestADODlg.cpp(195) : error C2065: "m_list " : undeclared identifier
D:\Microsoft Visual Studio\MyProjects\TestADO\TestADODlg.cpp(195) : error C2228: left of ".AddString " must have class/struct/union type
D:\Microsoft Visual Studio\MyProjects\TestADO\TestADODlg.cpp(201) : error C2228: left of ".SetCurSel " must have class/struct/union type
Generating Code...
Error executing cl.exe.

請問什麼原因那?

------------------------------------------------------------------------------------
http://www.vckbase.com/document/viewdoc/?id=496

把文章中連接Access的語句換成:
連接SQL資料庫:
m_pConnection- >Open("Provider=SQLOLEDB.1;Server=192.168.1.6;DATABASE=mysql;UID=sa;PWD=;","","",adModeUnknown);

其中Server是SQL伺服器的名稱,DATABASE是庫的名稱

Ⅵ 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());
}