當前位置:首頁 » 操作系統 » c如何調用資料庫

c如何調用資料庫

發布時間: 2023-03-26 19:10:22

A. 用c語言怎麼連接資料庫

c語言當然可以連接資料庫了。看你是想要連接什麼資料庫呢?各種資料庫都有很多相應的函數實現了。看你想要使用什麼技術了,比如說ado,odbc,,等等都可以連接資料庫。

B. 用C語言如何對Mysql資料庫進行操作

里的大部分代碼參考了MySQL發行包裡面的.c源文件,大家也可以去裡面找找相關的代碼,下面這段代碼實現了連接到本地MySQL伺服器上9tmd_bbs_utf8資料庫,從數據表tbb_user中根據輸入的userid取得該用戶的用戶名並列印輸出到終端。
if defined(_WIN32) || defined(_WIN64)為了支持windows平台上的編譯
#include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include "mysql.h"

我的機器上該文件在/usr/local/include/mysql下
定義MySQL資料庫操作的宏,也可以不定義留著後面直接寫進代碼
define SELECT_QUERY "select username from tbb_user where userid = %d" int main(int argc, char **argv)char **argv 相當於 char *argv[] {

MYSQL mysql,*sock;定義資料庫連接的句柄,它被用於幾乎所有的MySQL函數
MYSQL_RES *res;查詢結果集,結構類型
MYSQL_FIELD *fd ;包含欄位信息的結構
MYSQL_ROW row ;存放一行查詢結果的字元串數組
char qbuf[160];存放查詢sql語句字元串
if (argc != 2) { //檢查輸入參數 fprintf(stderr,"usage : mysql_select <userid>\n\n"); exit(1); } mysql_init(&mysql); if (!(sock = mysql_real_connect(&mysql,"localhost","dbuser","dbpwd","9tmd_bbs_utf8",0,NULL,0))) { fprintf(stderr,"Couldn't connect to engine!\n%s\n\n",mysql_error(&mysql)); perror(""); exit(1); } sprintf(qbuf,SELECT_QUERY,atoi(argv[1])); if(mysql_query(sock,qbuf)) { fprintf(stderr,"Query failed (%s)\n",mysql_error(sock)); exit(1); } if (!(res=mysql_store_result(sock))) { fprintf(stderr,"Couldn't get result from %s\n", mysql_error(sock)); exit(1); } printf("number of fields returned: %d\n",mysql_num_fields(res)); while (row = mysql_fetch_row(res)) { printf("Ther userid #%d 's username is: %s\n", atoi(argv[1]),(((row[0]==NULL)&&(!strlen(row[0]))) ? "NULL" : row[0])) ; puts( "query ok !\n" ) ; } mysql_free_result(res); mysql_close(sock); exit(0); return 0;

為了兼容大部分的編譯器加入此行
}
編譯的時候,使用下面的命令
gcc -o mysql_select ./mysql_select.c -I/usr/local/include/mysql -L/usr/local/lib/mysql -lmysqlclient (-lz) (-lm) 後面兩個選項可選,根據您的環境情況運行的時候,執行下面的命令
./mysql_select 1
將返回如下結果:
number of fields returned: 1 Ther userid #1 's username is: Michael query ok !

上面的代碼我想大部分都能看明白,不明白的可以參考一下MySQL提供的有關C語言API部分文檔,各個函數都有詳細說明,有時間我整理一份常用的API說明出來。

C. c語言如何調用Mysql資料庫文件並進行對資料庫的操作呢。

MYSQL m_sqlCon;//聲明
mysql_init(&m_sqlCon);//初始化
mysql_real_connect(&m_sqlCon, "127.0.0.1", abc, "root", "hibernate", atoi("3306"),NULL,0)//鏈接
mysql_query(&m_sqlCon, "SET NAMES GB2312"); //設置查詢編碼格式
res = mysql_query(&m_sqlCon,"select * from ms_sendlist where flag = 1 order by style desc");//查詢
mysql_query(&m_sqlCon, sql);//插入,刪除

D. 怎樣在C++中調用MYSQL資料庫中的數據

1、用CAPI連接MySQL資料庫有兩個步驟:
1)初始化一個連接句柄
2)穗虧拿建立連接
所用到的函數如下:
MYSQL *mysql_init(MYSQL *connection); // 初始化連接句柄
//成功返回MySQL結構指針,失敗返回NULL

MYSQL *mysql_real_connect(MYSQL *connection,
const char *server_host,
const char *sql_user_name,
const char *sql_password,
const char *db_name,
unsigned int port_number,
const char *unix_socket_name,
unsigned int flags); //建立連接
//成功返回MySQL結構指針,失敗返回NULL
以下是完整實例:

#include <iostream>
#include <fstream>
#include <猜搭cstdlib>
#include <mysql/mysql.h>

using namespace std;

void mysql_err_function(MYSQL * connection);

int main()
{
//freopen("input.txt","r",stdin);

MYSQL * connection;
connection = mysql_init(NULL);

if (!connection)
{
cout << "mysql_init failed!" << endl;

exit(-1);
}

if (!mysql_real_connect(connection,"localhost","root","123456","test",0,NULL,0))
{
cout <<空叢 "Connection To MySQL failed!" << endl;
mysql_err_function(connection);
}

cout << "Connection To MySQL Server is Success..." << endl;

string str;
getline(cin,str);

int res = 0;
int affected_count = 0;
while (str != "close" && str != "" && !res)
{
res = mysql_query(connection,str.c_str());

affected_count += mysql_affected_rows(connection);

if (res)
{
if (mysql_errno(connection))
{
cout << "Error " << mysql_errno(connection) << " : "
<< mysql_error(connection) << '\n' << endl;
break;
}
}
getline(cin,str);
}

cout << "Have affected " << affected_count << " rows!" << endl;

mysql_close(connection);
cout << "Connection To MySQL Server is closed..." << endl;

return 0;
}

void mysql_err_function(MYSQL * connection)
{
if (mysql_errno(connection))
{
cout << "Error " << mysql_errno(connection) << " : "
<< mysql_error(connection) << endl;

exit(-1);
}
}

E. 如何使用C#語言調用資料庫

1.C#連接連接Access

using System.Data;
1.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.

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(); //關閉連接 } }

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

F. 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)

G. c語言如何使用access資料庫

1、C/C++與資料庫交互,像 mssql/ mysql / oracle 等,一般都有成熟的第三方庫,這些庫裡面無非就是封裝了與資料庫通訊的方式和通訊協議搜一下要用的資料庫相關的 API 文檔,會說得很清楚任何文件都是二進制數據,關鍵是數據存儲的組織方式通用擴展名的文件,像gif/doc/jpg/wav,格式都是固定的。
2、舉個例子,連接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;
pBandRecordset.CreateInstance(__uuidof(Recordset));
// 執行語句
CString strSQL(L"SELECT * FROM [Band]");
m_pConnection->Execute((LPCTSTR)strSQL,NULL,0);
// 提取某一項 例如BandInfo
int iBandInfo = wcscmp(colum, L"BandInfo");
while(!recordsetPtr->adoEOF)
{
var = recordsetPtr->GetCollect(colum);
if(var.vt != VT_NULL)
strName = (LPCSTR)_bstr_t(var);
recordsetPtr->MoveNext();
}

H. 如何在c程序中調用access資料庫

c語言不能連接資料庫,只能用文件保存數據;
我在學習的時候也曾遇到過這樣的問題,請教老師,老師告訴我C語言主要用來開發系統的,還有就是用來開發游戲的。一般用文件保存數據。不會用到資料庫;
要用資料庫的語言有VB,java,c#,Dephi等等

I. 如何在C/C++程序中使用資料庫

一般要看使用的資料庫。如果 操作 sql server 需要用到 ADO 驅動,這種驅動使用MFC做的包裝類比較多一些,在控制台直接編寫代碼可能稍顯繁瑣。

如果操作mysql,在安裝mysql的時候,有相應的include頭文件和庫文件,可以在自己的IDE開發環境中進行設置。

J. 如何使用mysql的C介面訪問mysql資料庫

調用mysql資料庫API。
去官網下載mysql c API庫文件,然後安裝一下,每個調用資料庫的函數都有相關解釋,直接參照函數解釋進行編程就行了。
注意編寫makefile的時候把相關依賴庫加入

熱點內容
n皇後演算法 發布:2025-05-20 01:49:15 瀏覽:64
如何配置圖形電腦 發布:2025-05-20 01:47:51 瀏覽:390
及解壓 發布:2025-05-20 01:44:49 瀏覽:415
如何用計算器刷安卓 發布:2025-05-20 01:09:29 瀏覽:576
移動寬頻密碼重置後怎麼辦 發布:2025-05-20 01:02:04 瀏覽:808
php不是內部命令 發布:2025-05-20 00:41:09 瀏覽:97
淘寶圖片上傳用什麼軟體 發布:2025-05-20 00:40:55 瀏覽:346
mysql64位forlinux 發布:2025-05-20 00:37:25 瀏覽:345
工傷輔助器如何配置 發布:2025-05-20 00:25:13 瀏覽:602
opencv存儲圖片 發布:2025-05-20 00:16:10 瀏覽:953