c資料庫連接語句
① 幫忙用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++連接資料庫,求代碼,求指教,很急!
對於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控制項的話,連接字串可以自己生成,在控制項的屬性裡面找到拷貝就行,這種最簡單
③ 用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;
}
(3)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語言怎麼連接mysql資料庫
如鵬網上有詳細的視頻教程,楊中科的C語言也能幹大事,裡面講得很清楚。要是在這里講需要寫很多東西,累手,還沒有視頻直觀
⑥ c連接oracle資料庫的連接語句
連接代碼如下:
int main()
{
EXEC SQL BEGIN DECLARE SECTION;
char oc_passwd[101]; /*資料庫密碼*/
char oc_userid[101]; /*資料庫用戶名*/
char oc_dbname[101]; /*資料庫名*/
char oc_coad[101];
EXEC SQL END DECLARE SECTION;
memset(oc_passwd, 0x00, sizeof(oc_passwd));
memset(oc_userid, 0x00, sizeof(oc_userid));
memset(oc_dbname, 0x00, sizeof(oc_dbname));
/*取資料庫用戶名*/
strcpy(oc_userid, "userid");
/*取資料庫用戶密碼*/
strcpy(oc_passwd, "passwd") ;
/*取資料庫名*/
strcpy(oc_dbname, "dbname");
EXEC SQL CONNECT :oc_userid
IDENTIFIED BY :oc_passwd
USING :oc_dbname;
if (sqlca.sqlcode != 0)
{
printf("用戶名[%s]密碼[%s]資料庫[%s]\n", oc_userid, oc_passwd, oc_dbname);
printf("連接資料庫失敗,sqlcode=%d\n", sqlca.sqlcode);
return -1;
}
/*讀table取coad欄位*/
memset(oc_coad, 0x00, sizeof(oc_coad));
EXEC SQL SELECT coad
INTO :oc_coad
FROM table
WHERE 1=1;
if (sqlca.sqlcode == NORECORD)
{
printf("查詢無記錄\n");
return -1;
}
else if (sqlca.sqlcode != 0)
{
printf("查詢失敗,sqlcode=%d\n", sqlca.sqlcode);
return -1;
}
return 0;
}
⑦ c與資料庫連接的詳細步驟
C#連接資料庫有以下幾個步驟:
1:使用配置的資料庫連接串,創建資料庫連接 Connection 對象
2:構建操作的sql語句
3:定義command對象
4:打開數據連接
5:執行命令
舉一個例子,刪除操作
public class StudentService
{
//從配置文件中讀取資料庫連接字元串
private readonly static string connString = ConfigurationManager.ConnectionStrings["accpConnectionString"].ToString();
private readonly static string dboOwner = ConfigurationManager.ConnectionStrings["DataBaseOwner"].ToString();
AdoNetModels.Student model = new Student();
#region 刪除數據1
public int DeleteStudent(int stuID)
{
int result = 0;
// 資料庫連接 Connection 對象
SqlConnection connection = new SqlConnection(connString);
// 構建刪除的sql語句
string sql = string.Format("Delete From Student Where stuID={0}", stuID);
// 定義command對象
SqlCommand command = new SqlCommand(sql, connection);
try
{
connection.Open();
result = command.ExecuteNonQuery(); // 執行命令
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
return result;
}
#endregion
⑧ 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#怎麼和sql資料庫連接
1、打開Visual Studio 2008工具,點擊文件菜單,選擇新建下面的項目選項,如下圖所示。
⑩ c語言如何和資料庫連接
C函數庫沒有相應的資料庫連接介面函數。
只能夠嘗試用二進制或文本模式讀寫文件,來模擬相應的資料庫操作等。
可以嘗試下C++庫類,裡面有資料庫連接的介面