c資料庫連接測試
Ⅰ c++資料庫如何連接
1.c++連接連接access
程序代碼:
using system.data;
using system.data.oledb;
..
string strconnection="provider=microsoft.jet.oledb.4.0;";
strconnection+=@"data source=c:begaspnetnorthwind.mdb";
oledbconnection objconnection=new oledbconnection(strconnection);
..
objconnection.open();
objconnection.close();
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();
3.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();
4.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();
//關閉連接
Ⅱ c語言怎樣連接資料庫(c語言和資料庫連接)
1、配置ODBC數據源。
2、使用SQL函數進行連接。
對於1、配置數據源,配置完以後就可以編程操作資料庫了。
對於2、使用SQL函數進行連接,參考代碼如下:
#include
#include
#include
voidmain()
{
HENVhenv;//環境句柄
HDBChdbc;//數據源句柄
HSTMThstmt;//執行語句句柄
unsignedchardatasource[]="數據源名稱";//即源中設置的源名稱
unsignedcharuser[]="用戶名";//數襲此據庫的帳戶拍野迅名
unsignedcharpwd[]="密碼";//資料庫的密碼
unsignedcharsearch[]="selectxmfromstuwherexh=0";
SQLRETURNretcode;//記錄各SQL函數的返回情況
//分配環境句柄
retcode=SQLAllocEnv(&henv);//等介於(SQL_HANDLE_ENV,SQL_NULL
,&henv);
//設置ODBC環境版本號為3.0
retcode=(henv,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);
//分配連接句柄
retcode=(henv,&hdbc);//等介於(SQL_HANDLE_DBC,henv,&hdbc);
//設置連接屬性,登錄超時為*rgbValue秒(可以沒有)
//(hdbc,SQL_LOGIN_TIMEOUT,(SQLPOINTER)(rgbValue),0);
//直接連接數據源
//如果是windows身份驗證,第二、三參數可以是
,也可以是任何字串
//SQL_NTS即"
retcode=SQLConnect(hdbc,datasource,SQL_NTS,user,SQL_NTS,pwd,SQL_NTS);
//分配語句句柄
retcode=(hdbc,&hstmt);//等介於(SQL_HANDLE_STMT,hdbc,&hstmt);
//直接執行查詢語句
retcode=(hstmt,search,SQL_NTS);
//將數據緩沖區綁定資料庫中的相應脊塵欄位(i是查詢結果集列號,queryData是綁定緩沖區,BUFF_LENGTH是緩沖區長度)
SQLBindCol(hstmt,i,SQL_C_CHAR,queryData[i-1],BUFF_LENGTH,0);
//遍歷結果集到相應緩沖區queryData
SQLFetch(hstmt);
/*
*對遍歷結果的相關操作,如顯示等
*/
//注意釋放順序,否則會造成未知錯誤!
(SQL_HANDLE_STMT,hstmt);
(hdbc);
(SQL_HANDLE_DBC,hdbc);
(SQL_HANDLE_ENV,henv);
}
Ⅲ 用C語言怎麼實現與資料庫的連接
舉個例子巧念,連接SQL:
// 打開資料庫
strDBClass.Format(_T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;Jet OLEDB:Database Password=%s"), m_strUnEntryptMdbFilePath,m_strMDBPassword);
// 創建連接
HRESULT hr = m_pConnection.CreateInstance(_uuidof(Connection));
_ConnectionPtr m_pConnection->判頌Open(m_strDBClass,_T(""孝沖困),_T(""),adConnectUnspecified);
// 聲明表單指針
_RecordsetPtr pBandRecordset;
Ⅳ 在VS里C#中怎麼實現資料庫的連接
一個簡單的方法就是拖入sql datasource控制項 連接資料庫 完成後 將sql datasource控制項刪除 打開web.config就能看到生成的資料庫連接字元串
Ⅳ C/C++ 資料庫連接方法,高分
建議用ado連接,網上的ado封裝好的庫有很多,隨便下一個就行。
包含了頭文件和cpp文件後,可以這樣
CADORecordset* pRs = new CADORecordset((static_cast<CFrenchApp *>(AfxGetApp()))->g_pDb);
Sql1="select word,wordtype,meaning,tag,id from word "+Where;
int i=0;
if(pRs->Open((LPCTSTR)Sql1))
{
while(!pRs->IsEof())
{
pRs->GetFieldValue(0,word[i].word);
pRs->GetFieldValue(3,word[i].tag);
pRs->GetFieldValue(1,word[i].wordtype);
pRs->GetFieldValue(2,word[i].meaning);
pRs->GetFieldValue(4,word[i].id);
pRs->MoveNext();
i++;
}
pRs->Close();
}
m_max=i;
m_cur=0;
delete pRs;
這樣就可以得到數悉伍閉據庫睜裂里的東橘碧西
Ⅵ 用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)、遞歸搜索
Ⅶ 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++實現與資料庫的連接
用VC中的MFC吧,很好上手
#include <afxdb.h>
/* 連接資料庫 */
CDatabase db;
BOOL bRtn;
try {
bRtn = db.OpenEx("DSN=數據源名;UID=sa", CDatabase::noOdbcDialog);
}catch (CDBException *pDBEx) {
pDBEx->ReportError();
}catch (CMemoryException *pMemEx) {
pMemEx->ReportError();
}
if (!bRtn)
printf("連接資料庫失敗!");
/* 操作結束後,關閉資料庫 */
db.Close();
添加記錄操作
#include <afxdb.h>
CDatabase db;
BOOL bRtn;
CString sql;
/* 1、連接資料庫,見(1) */
/* 2、生成INSERT語句,叢肆稿賦給sql,例如: */
sql = "insert into student_table (s_sID, s_sName, s_sAge) values (『001』, 『ZhangSan』, 20);" ;
/* 3、往資料庫中添加紀錄 */
try {
db.ExecuteSQL(sql);
} catch (CDBException *pDBEx) {
pDBEx->ReportError();
}
/* 4、關閉資料庫 */
db.Close();
刪除記錄操作
#include <afxdb.h>
CDatabase db;
BOOL bRtn;
CString sql;
/* 1、連接資料庫,見(1) */
/* 2、生成DELETE語句,賦給sql,例如: */
sql = "delete from student_table where s_SID =』001』;" ;
/* 3、從資料庫中刪除紀錄 */
try {
db.ExecuteSQL(sql);
} catch (CDBException *pDBEx) {
pDBEx->ReportError();
}
/* 4、關閉資料庫 */
db.Close();
修改記錄操作
#include <afxdb.h>
CDatabase db;
BOOL bRtn;
CString sql;
/* 1、連接資料庫,見(1) */
/* 2、生成UPDATE語句,賦給sql,例如: */
sql = "update from student_table set s_sName=『LiSi』,s_sAge=21 where s_SID =『001』;" ;
/* 3、更新資料庫中的紀錄 */
try {
db.ExecuteSQL(sql);
} catch (CDBException *pDBEx) {
pDBEx->ReportError();
}
/* 4、關閉資料庫 */
db.Close();
查詢、統計操作
#include <myRecordset.h>滲孝
CDatabase db;
BOOL bRtn;
CString sql;
/* 1、連雹渣接資料庫,見(1) */
/* 2、生成查詢/統計語句,賦給sql,例如: */
sql = "Select * From student_table where s_sAge=20;" ;
/* 3、打開記錄集,查詢/統計 */
CMyRecordset rs(&db);
try {
bRtn = rs.Open(CRecordset::snapshot,sql);
} catch(CDBException *pDBEx) {
pDBEx->ReportError();
} catch(CMemoryException *pMemEx) {
pMemEx->ReportError();
}
if(!bRtn) {
AfxMessageBox("Query table failed!",MB_OK|MB_ICONERROR);
return ;
}
/* 4、逐條獲取查詢結果 */
for(rs.MoveFirst();!rs.IsEOF();rs.MoveNext()) {
// TODO: Add code here
}
/* 5、關閉記錄集、資料庫 */
rs.Close();
db.Close();
註:對連接查詢,可以先創建視圖,再對視圖進行查詢。
Ⅸ c語言如何和資料庫連接
C函數庫沒有相應的資料庫連接介面函數。
只能夠嘗試用二進制或文本模式讀寫文件,來模擬相應的資料庫操作等。
可以嘗試下C++庫類,裡面有資料庫連接的介面
Ⅹ c++怎麼連接access資料庫
環境配置:
1. 先安裝你的Access資料庫(微軟Office 2016中含有或者單獨下載,下載地址:http://msdn.itellyou.cn/ 左側選擇應用程序一欄,注意選擇下載64位,即標有X64的)
特殊情況查看意外解決方案 (A)
2. 安裝Microsoft Access database engine 2007,他的作用暫時可理解為我們所寫的程序與Access之間的溝通橋梁--「傳話人」。
Microsoft Access database engine 2010(可以安裝,但後面的代碼是2007的,所以暫時建議使用2007)
下載地址:https://www.microsoft.com/zh-cn/download/details.aspx?id=13255
Microsoft Access database engine 2007
下載地址:https://www.microsoft.com/zh-cn/download/details.aspx?id=23734
特殊情況查裂禪看意外解決方案 (C)
連接與測試代碼:
本例代碼使用VS2010以上版本測試
建議去文末下載寫好的含注釋的測試代碼看。
1. 新建你的資料庫表
打開Access
選擇空白資料庫,為你的資料庫中表項起一個名字 如 Test
設計你的存儲表格
本例附有測試表格database1.accdb
2.
在你程序的stdafx.h頭文件中加入
#import"C:/ProgramFiles/CommonFiles/System/ADO/msado15.dll"
rename("EOF","adoEOF"), rename("BOF","adoBOF")
(如果載入失敗的話,去c:\program files\common files\system\ado查看是否有msado15.dll)
3.測試代碰察碼介紹
// LinkDBForHX.cpp : 定義控制台應用程序的入口點。
[cpp] view plain
#include "stdafx.h"
#include<iostream>//atlstr
#include<atlstr.h>
using namespace ADODB;
using namespace std;
class AdoAccess {
public:
_ConnectionPtr HX_pConnection; // 資料庫指針
_RecordsetPtr HX_pRecordset; // 命令指針
_CommandPtr HX_pCommand; // 記錄指針
void OnInitADOConn() {
::CoInitialize(NULL);
try
{
HX_pConnection.CreateInstance(__uuidof(Connection));//等價於 //HX_pConnection.CreateInstance("ADODB.Connection");
//此句包含定位你資料庫的所需的訪問信息
_bstr_t strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;Persist Security Info=False ";
//測試//_bstr_t strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Database1.accdb;Persist Security Info=False";//此句包含定位你資料庫的所需的訪問信息
//測試//_bstr_t strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Driver = { Microsoft Access Driver(*.mdb, *.accdb) }; DBQ =Database1.accdb;Persist Security Info=False ";
//此句包含定位你資料庫的所需的訪問信息
//連接master數笑源茄據庫,無密碼。
HX_pConnection->Open(strConnect,"","",adModeUnknown); //連接資料庫
cout << "連接成功,並獲得智能指針" << endl;
}
catch (_com_error e)
{
cout <<e.Description() << endl;
}
}
void ExitConnect() {
if (HX_pRecordset != NULL)
HX_pRecordset->Close();
HX_pConnection->Close();
::CoUninitialize();
}
};
int main()
{
AdoAccess dataBase;
//初始化
dataBase.OnInitADOConn();
dataBase.HX_pRecordset.CreateInstance("ADODB.Recordset");
//選擇名為Test的表格
dataBase.HX_pRecordset->Open("select * from Test",
dataBase.HX_pConnection.GetInterfacePtr(),
adOpenDynamic,
adLockOptimistic,
adCmdText);
int i = 0;
//讀取其中的name欄位所有數據,並顯示
while (!dataBase.HX_pRecordset->adoEOF)
{
_variant_t var;
string strValue;
var = dataBase.HX_pRecordset->GetCollect("name");
//其他類似,都是通過HX_pRecordset傳遞SQL語句執行查找、添加、刪除等命令
if (var.vt != VT_NULL)
strValue = _com_util::ConvertBSTRToString((_bstr_t)var);
++i;
cout << "name " << i << " " << strValue << endl;;
dataBase.HX_pRecordset->MoveNext();
}
//卸載com組件
dataBase.ExitConnect();
int xxxx = 0;
cout << "輸入數字結束\n";
cin >> xxxx;
return 0;
}
意外情況解決方案
A 描述:未在本地計算機上注冊「microsoft.ACE.oledb.12.0」提供程序。
請正確安裝環境配置中的第一步
B 若A無法解決問題。
選擇 該應用程序的 應用程序池 ------>選擇高級設置--------->啟用32位應用程序 ------->true
操作如下:
按下win + R
在彈出的對話框中輸入inetmgr,然後按回車鍵
選擇最左側
點擊應用程序池
再點擊下圖的DefaultAPPPool
選擇高級設置
選擇啟用32位應用程序 ---置為True.
最後選擇確認保存
C 重新安裝 Microsoft Access databaseengine 2007
D 程序若提示缺少符號集,請下載相關符號集或者在聯網狀態下動態載入