當前位置:首頁 » 操作系統 » c連接遠程資料庫

c連接遠程資料庫

發布時間: 2022-12-27 00:27:18

❶ 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/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)

❸ 如何遠程訪問MySQL資料庫詳解

默認情況下,mysql只允許本地登錄,如果要開啟遠程連接,則需要修改/etc/mysql/my.conf文件。

一、修改/etc/mysql/my.conf
找到bind-address = 127.0.0.1這一行
改為bind-address = 0.0.0.0即可

二、為需要遠程登錄的用戶賦予許可權
1、新建用戶遠程連接mysql資料庫
grant all on *.* to admin@'%' identified by '123456' with grant option;
flush privileges;
允許任何ip地址(%表示允許任何ip地址)的電腦用admin帳戶和密碼(123456)來訪問這個mysql server。
注意admin賬戶不一定要存在。

2、支持root用戶允許遠程連接mysql資料庫
grant all privileges on *.* to 'root'@'%' identified by '123456' with grant option;
flush privileges;

三、查看系統用戶

❹ C/S模式,C#如何遠程連接sql2008資料庫

在資料庫連接字元串中使用外網的網址即可
//通過IP地址連接,必需確保SQL伺服器開啟1433埠和檢查SQL網路連接啟用TCP/IP協議
string serverInfo = string.Format("Data Source={0},1433;Network Library=DBMSSOCN;Initial Catalog=", serverIP);
string pwd = ";User ID=xxx;PWD=xxx";
string connString = string.Format("{0}{1}{2}", serverInfo, "資料庫名稱", pwd);

linux下c++遠程連接oracle資料庫

你說的復合結構應該是結構體吧。若是舉個例子給你看看

/*
* sample2.pc
*
* This program connects to ORACLE, declares and opens a cursor,
* fetches the names, salaries, and commissions of all
* salespeople, displays the results, then closes the cursor.
*/
#include <stdio.h>
#include <sqlca.h>
#define UNAME_LEN 20
#define PWD_LEN 40
/*
* Use the precompiler typedef』ing capability to create
* null-terminated strings for the authentication host
* variables. (This isn』t really necessary--plain char *』s
* does work as well. This is just for illustration.)
*/
typedef char asciiz[PWD_LEN];
EXEC SQL TYPE asciiz IS STRING(PWD_LEN) REFERENCE;
asciiz username;
asciiz password;
struct emp_info
{
asciiz emp_name;
float salary;
float commission;
};
/* Declare function to handle unrecoverable errors. */
void sql_error();
main()
{
struct emp_info *emp_rec_ptr;
/* Allocate memory for emp_info struct. */
if ((emp_rec_ptr =
(struct emp_info *) malloc(sizeof(struct emp_info))) == 0)
{
fprintf(stderr, "Memory allocation error. ");
exit(1);
}
/* Connect to ORACLE. */
strcpy(username, "SCOTT");
strcpy(password, "TIGER");
EXEC SQL WHENEVER SQLERROR DO sql_error("ORACLE error--");
EXEC SQL CONNECT :username IDENTIFIED BY :password;
printf(" Connected to ORACLE as user: %s ", username);
/* Declare the cursor. All static SQL explicit cursors
* contain SELECT commands. 』salespeople』 is a SQL identifier,
* not a (C) host variable.
*/
EXEC SQL DECLARE salespeople CURSOR FOR
SELECT ENAME, SAL, COMM FROM EMP WHERE JOB LIKE 』SALES%』;
/* Open the cursor. */
EXEC SQL OPEN salespeople;
/* Get ready to print results. */
printf(" The company』s salespeople are-- ");
printf("Salesperson Salary Commission ");
printf("----------- ------ ---------- ");
/* Loop, fetching all salesperson』s statistics.
* Cause the program to break the loop when no more
* data can be retrieved on the cursor.
*/
EXEC SQL WHENEVER NOT FOUND DO break;
for (;;)
{
EXEC SQL FETCH salespeople INTO :emp_rec_ptr;
printf("%-11s%9.2f%13.2f ", emp_rec_ptr->emp_name,emp_rec_ptr->salary, emp_rec_ptr->commission);
}
/* Close the cursor. */
EXEC SQL CLOSE salespeople;
printf(" Arrivederci. ");
EXEC SQL COMMIT WORK RELEASE;
exit(0);
}
void sql_error(msg) char *msg;
{
char err_msg[512];
int buf_len, msg_len;
EXEC SQL WHENEVER SQLERROR CONTINUE;
printf(" %s ", msg);
/* Call sqlglm() to get the complete text of the
* error message.
*/
buf_len = sizeof (err_msg);
sqlglm(err_msg, &buf_len, &msg_len);
printf("%.*s ", msg_len, err_msg);
EXEC SQL ROLLBACK RELEASE;
exit(1);
}

❻ C#(或者別的語言)如何連接兩個遠程資料庫

介紹四個辦法:

  1. 效率低,但是操作簡單用OpenRowSet方法直接在SQL上建立查詢

  2. 效率低,但是方便,用ACCESS的ODBC庫

  3. 效率高,編程要使用邏輯性強一點,遍歷兩個資料庫的數據表,使用臨時表作為連接池

  4. 效率高,操作簡單,利用ACCESS連接表

OpenRowset用法(例連接兩表查詢):

Select*from表AInnerJoin表BOpenRowSet[Driver={SQLServer};Server=IP;UID=...;PWD=...;DataBase=...]On條件;

ODBC方法,把C#連接ACCESS空資料庫,利用ACCESS的ODBC驅動去連接外部SQL遠程表

Select*from表AInnerJOIN表BINODBC[ODBC:Driver={SQLServer};Server=...;uid=...;pwd=...;DataBase=...]as查詢2On表A.欄位=查詢2.欄位;

遍歷數據集合是最常用的辦法,建立一個臨時表在本地資料庫也好在異地資料庫也好,先去查詢Server表,查詢出來循環遍歷他,遍歷過程中把遍歷的變數去作為另一個查詢的參數,最後把另一個查詢出來的數據逐條插入到臨時表中,每一次操作都先刪除臨時表再重新插入初始化他,這樣就達到了用連接池來分析大量數據的目的,例(用Server1上的表A去匹配查詢Server2上的表B,再插入Server3上的表C)

usingSystem.Data;
usingSystem.SqlClient;
...
//插入數據的過程
voidcharu(stringID)//用ID去查詢Server2的表B,插入到Server3的表C
{
SqlConnectioncnn=newSqlConnection();
cnn.ConnectionString="連接Server2的字元串";
try
{
cnn.Open();
DataSetds=newDataSet;
SqlDataAdaptersda=newSqlDataAdapter("Select*from表BwhereID='"+ID+"'",cnn);
sda.Fill(ds);//查出單條數據
SqlConnectioncnn1=newSqlConnection();
cnn1.ConnectionString="連接Server3的字元串";
cnn1.Open();
//...插入查詢出來的數據到Server3的表C
DataSetds1=newDataSet;
SqlDataAdaptersda1=newSqlDataAdapter("InsertInto表C(欄位)values('"+ds.Tables[0].Rows[0]["插入的欄位"].ToString()+"')",cnn1);
sda1.Fill(ds1);

}
catch
{
//..錯誤信息
}
finnaly
{
cnn.Close();
}
}
}
voidlianjiechaxun()
{
SqlConnectioncnn=newSqlConnection();
cnn.ConnectionString="連接Server1的字元串";
try
{
cnn.Open();
DataSetds=newDataSet;
SqlDataAdaptersda=newSqlDataAdapter("Select*from表A",cnn);
sda.Fill(ds);
for(inti=0;i<ds.Tables[0].Rows.Count;i++)
{
charu(ds.Tabels[0].Rows[i]["ID"].ToString());
//把表A的ID作為參數
}
}
catch
{
//..錯誤信息
}
finnaly
{
cnn.Close();
}
}

用ACCESS連接表是最簡單的,但是比上面的速度要慢一點,最重要的數據不安全,ACCESS密碼是可以破解的。上面的如果用三層結構寫,反編譯也破解不了。在網上看一下ACCESS怎麼建立SQL Server遠程連接表,這些表將當作ACCESS表可以在ACCESS里直接使用,建立好查詢,可以直接調用。

❼ Wincc的C腳本如何連接到遠程SQLServer資料庫具體代碼如何

1、建立存儲
CREATE PROCere[owner.]procerename[;number]

[[(]@parameter_name datatype[=default][OUTput]

[,@parameter_name datatype[=default][OUTput]]...[)]]

[WITH RECOMPILE]

AS SQL_statements

2、存儲規則:

[EXECute][@return-status=]

[[[server.]database.]owner.]procerename[;number]

[[@parameter_name=]value|[@parameter_name=]@varialbe[OUTput]

[,[@parameter_name=]value|[@parameter_name=]@variable[OUTput]...]]

[WITH RECOMPILE]

❽ 如何遠程訪問MySQL資料庫詳解

一、連接遠程資料庫:
1、顯示密碼
如:MySQL
連接遠程資料庫(192.168.5.116),埠「3306」,用戶名為「root」,密碼「123456」
C:/>mysql
-h
192.168.5.116
-P
3306
-u
root
-p123456
2、隱藏密碼
如:MySQL
連接本地資料庫,用戶名為「root」,
C:/>mysql
-h
localhost
-u
root
-p
Enter
password:
二、配置mysql允許遠程鏈接
默認情況下,mysql帳號不允許從遠程登陸,只能在localhost登錄。本文提供了二種方法設置mysql可以通過遠程主機進行連接。
一、改表法
在localhost登入mysql後,更改
"mysql"
資料庫里的
"user"
表裡的
"host"
項,將"localhost"改稱"%"
例如:
#mysql
-u
root
-p
Enter
password:
……
mysql>
mysql>update
user
set
host
=
'%'
where
user
=
'root';
mysql>select
host,
user
from
user;
二、授權法
例如:
你想myuser使用mypassword(密碼)從任何主機連接到mysql伺服器的話。
mysql>GRANT
ALL
PRIVILEGES
ON
*.*
TO
'myuser'@'%'IDENTIFIED
BY
'mypassword'
WITH
GRANT
OPTION;
如果你想允許用戶myuser從ip為192.168.1.6的主機連接到mysql伺服器,並使用mypassword作為密碼
mysql>GRANT
ALL
PRIVILEGES
ON
*.*
TO
'myuser'@'192.168.1.3'IDENTIFIED
BY
'mypassword'
WITH
GRANT
OPTION;
mysql>FLUSH
PRIVILEGES
使修改生效,就可以了
常見問題:
1、在採用法二授權法之後,無法在本地登錄mysql(如:#mysql
-u
root
-p
-h
192.168.5.116
Enter
password:
ERROR
1045
(28000):
Access
denied
for
user
'root'@'loadb116'
(using
password:
YES)
上例中loadb116是主機名.
解決方法:
1、這時可以使用:mysql
-u
root
-p
登錄,進入到mysql後。
mysql>
grant
all
privileges
on
*.*
to
'root'@'loadb116'
identified
by
'123456'
with
grant
option;
Query
OK,
0
rows
affected
(0.00
sec)
mysql>
flush
privileges;
Query
OK,
0
rows
affected
(0.00
sec)
2、在本地使用ip地址登錄
#
mysql
-u
root
-p
-h
192.168.5.116
Enter
password:
Welcome
to
the
MySQL
monitor.
Commands
end
with
;
or
/g.
Your
MySQL
connection
id
is
60
Server
version:
5.1.45
MySQL
Community
Server
(GPL)
Type
'help;'
or
'/h'
for
help.
Type
'/c'
to
clear
the
buffer.
mysql>

❾ 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

❿ 如何連接遠程Mysql資料庫

連接遠程mysql資料庫需要連接工具,市面上有很多連接工具如 mysql-font、Navicat for MySQL 等等 下面以Navicat for MySQL為例說明一下:(我用的mac版的)

1、下載Navicat for MySQL安裝包

2、按照流程安裝

3、打開Navicat for MySQL如圖並點擊新建連接

5、點擊確定,ok

熱點內容
spl編程 發布:2025-05-11 00:25:14 瀏覽:63
linux搭建android開發環境 發布:2025-05-11 00:18:45 瀏覽:947
web本地存儲 發布:2025-05-11 00:13:33 瀏覽:360
為什麼暗格里的密碼搜不到了 發布:2025-05-11 00:13:31 瀏覽:942
oracle存儲過程使用變數 發布:2025-05-11 00:10:07 瀏覽:741
用安卓下載蘋果的軟體叫什麼 發布:2025-05-11 00:08:22 瀏覽:115
斷牙腳本 發布:2025-05-11 00:04:21 瀏覽:68
sim卡的密碼怎麼設置密碼 發布:2025-05-10 23:41:09 瀏覽:716
自定義緩存註解 發布:2025-05-10 23:40:06 瀏覽:118
sqltext類型長度 發布:2025-05-10 23:30:21 瀏覽:979