c資料庫連接代碼
Ⅰ 求c#編寫的登錄界面資料庫連接代碼
using System.Data.sqlClient;
string strconn="server=(local);database=xwxt;uid=資料庫用戶名;pwd=資料庫密碼";
sqlconnection conn=new sqlconnection(strconn);
string str="select count(*) from denglu where username='"+txtuser.Text+"' and password='"+txtpassword.Text+"'";
SqlCommand cmd=new SqlCommand(str,conn);
conn.open;
int count=Convert.ToInt32(cmd.ExecuteScalar());
if(count>0)
{ Response.Redirect("index.aspx");
}
else
{
Response.Write("<script> alert('用戶名或密碼不正確!')</script>");
}
conn.Close();
Ⅱ 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資料庫
1、配置ODBC數據源。
2、使用SQL函數進行連接。
對於1、配置數據源,配置完以後就可以編程操作資料庫了。
對於2、使用SQL函數進行連接,參考代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<windows.h>
#include<sql.h>
#include<sqlext.h>
void
main()
{
HENV
henv;
//環境句柄
HDBC
hdbc;
//數據源句柄
HSTMT
hstmt;
//執行語句句柄
unsigned
char
datasource[]="數據源名稱";
//即源中設置的源名稱
unsigned
char
user[]=
"用戶名";
//資料庫的帳戶名
unsigned
char
pwd[]=
"密碼";
//資料庫的密碼
unsigned
char
search[]="select
xm
from
stu
where
xh=0";
SQLRETURN
retcode;
//記錄各SQL函數的返回情況
//
分配環境句柄
retcode=
SQLAllocEnv(&henv);
//
等介於
SQLAllocHandle(SQL_HANDLE_ENV,
SQL_NULL
,
&henv);
//
設置ODBC環境版本號為3.0
retcode=
SQLSetEnvAttr(henv,
SQL_ATTR_ODBC_VERSION,
(void*)SQL_OV_ODBC3,
0);
//
分配連接句柄
retcode=
SQLAllocConnect(henv,&hdbc);
//
等介於
SQLAllocHandle(SQL_HANDLE_DBC,
henv,
&hdbc);
//設置連接屬性,登錄超時為*rgbValue秒(可以沒有)
//
SQLSetConnectAttr(hdbc,
SQL_LOGIN_TIMEOUT,
(SQLPOINTER)(rgbValue),
0);
//直接連接數據源
//
如果是windows身份驗證,第二、三參數可以是
Ⅳ C語言與資料庫連接時的代碼
SqlDataAdapter sda; //聲明數據適配器對象
DataSet ds; //聲明數據集對象
SqlCommand sc;
string connStr = "SERVER=(local);DATABASE=db_GoodsManage;UID=sa;PWD=";
SqlConnection conn; //聲明鏈接對象
//連接資料庫
public SqlConnection getConn()
{
//實例化SqlConnection
conn = new SqlConnection(connStr);
conn.Open();
return conn;
}
Ⅳ 用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;
}
(5)c資料庫連接代碼擴展閱讀
C語言使用注意事項:
1、指針是c語言的靈魂,一定要靈活的使用它:
(1)、指針的聲明,創建,賦值,銷毀等
(2)、指針的類型轉換,傳參,回調等
2、遞歸調用也會經常用到:
(1)、遞歸遍歷樹結構
(2)、遞歸搜索
Ⅵ 用c語言怎麼連接資料庫呢
25.2.2. C API函數概述
這里歸納了C API可使用的函數,並在下一節詳細介紹了它們。請參見25.2.3節,「C API函數描述」。
函數
描述
mysql_affected_rows()
返回上次UPDATE、DELETE或INSERT查詢更改/刪除/插入的行數。
mysql_autocommit()
切換 autocommit模式,ON/OFF
mysql_change_user()
更改打開連接上的用戶和資料庫。
mysql_charset_name()
返回用於連接的默認字元集的名稱。
mysql_close()
關閉伺服器連接。
mysql_commit()
提交事務。
mysql_connect()
連接到MySQL伺服器。該函數已不再被重視,使用mysql_real_connect()取代。
mysql_create_db()
創建資料庫。該函數已不再被重視,使用SQL語句CREATE DATABASE取而代之。
mysql_data_seek()
在查詢結果集中查找屬性行編號。
mysql_debug()
用給定的字元串執行DBUG_PUSH。
mysql_drop_db()
撤銷資料庫。該函數已不再被重視,使用SQL語句DROP DATABASE取而代之。
mysql_mp_debug_info()
讓伺服器將調試信息寫入日誌。
mysql_eof()
確定是否讀取了結果集的最後一行。該函數已不再被重視,可以使用mysql_errno()或mysql_error()取而代之。
mysql_errno()
返回上次調用的MySQL函數的錯誤編號。
mysql_error()
返回上次調用的MySQL函數的錯誤消息。
mysql_escape_string()
為了用在SQL語句中,對特殊字元進行轉義處理。
mysql_fetch_field()
返回下一個表欄位的類型。
mysql_fetch_field_direct()
給定欄位編號,返回表欄位的類型。
mysql_fetch_fields()
返回所有欄位結構的數組。
mysql_fetch_lengths()
返回當前行中所有列的長度。
mysql_fetch_row()
從結果集中獲取下一行
mysql_field_seek()
將列游標置於指定的列。
mysql_field_count()
返回上次執行語句的結果列的數目。
mysql_field_tell()
返回上次mysql_fetch_field()所使用欄位游標的位置。
mysql_free_result()
釋放結果集使用的內存。
mysql_get_client_info()
以字元串形式返回客戶端版本信息。
mysql_get_client_version()
以整數形式返回客戶端版本信息。
mysql_get_host_info()
返回描述連接的字元串。
mysql_get_server_version()
以整數形式返回伺服器的版本號。
mysql_get_proto_info()
返回連接所使用的協議版本。
mysql_get_server_info()
返回伺服器的版本號。
mysql_info()
返回關於最近所執行查詢的信息。
mysql_init()
獲取或初始化MYSQL結構。
mysql_insert_id()
返回上一個查詢為AUTO_INCREMENT列生成的ID。
mysql_kill()
殺死給定的線程。
mysql_library_end()
最終確定MySQL C API庫。
mysql_library_init()
初始化MySQL C API庫。
mysql_list_dbs()
返回與簡單正則表達式匹配的資料庫名稱。
mysql_list_fields()
返回與簡單正則表達式匹配的欄位名稱。
mysql_list_processes()
返回當前伺服器線程的列表。
mysql_list_tables()
返回與簡單正則表達式匹配的表名。
mysql_more_results()
檢查是否還存在其他結果。
mysql_next_result()
在多語句執行過程中返回/初始化下一個結果。
mysql_num_fields()
返回結果集中的列數。
mysql_num_rows()
返回結果集中的行數。
mysql_options()
為mysql_connect()設置連接選項。
mysql_ping()
檢查與伺服器的連接是否工作,如有必要重新連接。
mysql_query()
執行指定為「以Null終結的字元串」的SQL查詢。
mysql_real_connect()
連接到MySQL伺服器。
mysql_real_escape_string()
考慮到連接的當前字元集,為了在SQL語句中使用,對字元串中的特殊字元進行轉義處理。
mysql_real_query()
執行指定為計數字元串的SQL查詢。
mysql_refresh()
刷新或復位表和高速緩沖。
mysql_reload()
通知伺服器再次載入授權表。
mysql_rollback()
回滾事務。
mysql_row_seek()
使用從mysql_row_tell()返回的值,查找結果集中的行偏移。
mysql_row_tell()
返回行游標位置。
mysql_select_db()
選擇資料庫。
mysql_server_end()
最終確定嵌入式伺服器庫。
mysql_server_init()
初始化嵌入式伺服器庫。
mysql_set_server_option()
為連接設置選項(如多語句)。
mysql_sqlstate()
返回關於上一個錯誤的SQLSTATE錯誤代碼。
mysql_shutdown()
關閉資料庫伺服器。
mysql_stat()
以字元串形式返回伺服器狀態。
mysql_store_result()
檢索完整的結果集至客戶端。
mysql_thread_id()
返回當前線程ID。
mysql_thread_safe()
如果客戶端已編譯為線程安全的,返回1。
mysql_use_result()
初始化逐行的結果集檢索。
mysql_warning_count()
返回上一個SQL語句的告警數。 詳見:http://dev.mysql.com/doc/refman/5.1/zh/apis.html#c-api-function-overview
http://dev.mysql.com/doc/refman/5.0/en/c.html
Ⅶ C#中連接資料庫的代碼是什麼 寫在什麼地方的
原則是寫在任何地方都可以,主要用來連接字元串。寫法如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;//首先導入命名空間
using System.Data.SqlClient;//首先導入命名空間
namespace EJ_Market.Model.Common
{
class DataBase
{
SqlConnection con = null;
public SqlConnection GetCon()
if (con == null)
{
con=new
SqlConnection("server=www.test.e.com;uid=sa;pwd=ln881205;database=EJmarket")//server=.點代表本地伺服器;uid是混合模式登陸的賬號;pwd是混合模式登陸的密碼database是資料庫名稱
}
if (con.State == ConnectionState.Closed)
{
con.Open();
}
return con;
}
//end GetCon public void GetClose()
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}//end GetClose
}//end class
}//end namespace
(7)c資料庫連接代碼擴展閱讀:
連接資料庫、操作資料庫,本質是利用資料庫提供的動態鏈接庫MySql.Data.dll進行操作。MySql.Data.dll提供以下8個類:
MySqlConnection: 連接MySQL伺服器資料庫。
MySqlCommand:執行一條sql語句。
MySqlDataReader: 包含sql語句執行的結果,並提供一個方法從結果中閱讀一行。
MySqlTransaction: 代表一個SQL事務在一個MySQL資料庫。
MySqlException: MySQL報錯時返回的Exception。
MySqlCommandBuilder: Automatically generates single-table commands used to reconcile changes made to a DataSet with the associated MySQL database.
MySqlDataAdapter: Represents a set of data commands and a database connection that are used to fill a data set and update a MySQL database.
MySqlHelper: Helper class that makes it easier to work with the provider.
Ⅷ 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語言怎麼連接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;
}
Ⅹ 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();
//關閉連接