本文目錄一覽:
- 1、請問哪位會寫php連接mysql數據庫的代碼。
- 2、用C語言如何對MySQL數據庫進行操作
- 3、實例講解如何使用C++操作MySQL數據庫類
- 4、jdbc連接數據庫的代碼問題jdbc連接mysql數據庫
- 5、c語言怎麼連接mysql數據庫 代碼
請問哪位會寫php連接mysql數據庫的代碼。
include ‘mysql.php’;
$server=”localhost”;
$user=”用戶名”;
$psw=”密碼”;
$database=”數據庫”;
$db = new Mysql();
$db-connect($server, $user, $psw, $database);
unset($server, $user, $psw, $database);
mysql.php是個數據庫連接類,內容如下:
?php
class Mysql{
var $qryNum = 0;
var $qryInfo = ”;
var $qryTime = 0.0;
var $debug = false;
var $connId;
var $tblPrefix = ”;
var $tblFields = array();
var $lastQuery ;
var $openedQueries;//沒有釋放的查詢
var $transaction;
function Mysql() {
$this-debug = 0;
defined(‘UNBUFFERED’) or define(‘UNBUFFERED’,1);
}
function connect($host, $user, $pass, $name) {
$this-connId = @mysql_connect($host, $user, $pass) OR $this-halt(“Cann’t connect to server”);
$this-selectDb( $name );
return;
}
function selectDb($name) {
return @mysql_select_db($name, $this-connId) OR $this-halt();
}
function insert($table, $data) {
$fields = $this-getFields($table);
$values = $columns = array();
foreach ($fields as $field) {
$column = $field[‘Field’];
if ( $field[‘Extra’] == ‘auto_increment’ ) {
$values[] = ‘null’;
} else if ( array_key_exists($column, $data) ) {
$values[] = “‘” . $data[$column] . “‘”;
} else {
$values[] = “‘” . $field[‘Default’] . “‘”;
}
$columns[] = $column;
}
$sql = “INSERT INTO $table(” . implode(‘,’, $columns) .’) VALUES(‘. implode(‘,’, $values) .’)’;
return $this-query($sql, UNBUFFERED);
}
function update($table, $data, $conds) {
$updates = array();
$fields = $this-getFields($table);
foreach ($fields as $field) {
$column = $field[‘Field’];
if (isset($data[$column])) {
$updates[] = “$column='” . $data[$column] . “‘”;
}
}
$sql = “UPDATE $table SET “. implode(‘,’, $updates) .” WHERE $conds”;
return $this-query($sql, UNBUFFERED);
}
function delete($table, $conds) {
return $this-query(“DELETE FROM $table WHERE $conds”, UNBUFFERED);
}
function select($table, $columns = ‘*’, $conds = 1) {
return $this-query(“SELECT $columns FROM $table WHERE $conds”);
}
function getFields($table) {
if (array_key_exists($table, $this-tblFields)) {
return $this-tblFields[$table];
}
$this-query(“DESC $table”);
return $this-tblFields[$table] = $this-fetchAll();
}
function fetchAll($qryId = 0) {
$rtn = array();
$qryId || $qryId = $this-lastQuery;
while ($row = $this-fetchAssoc($qryId)) {
$rtn[] = $row;
}
return $rtn;
}
function fetchOne($sql) {
$rst = $this-query($sql);
return mysql_fetch_array($rst, MYSQL_ASSOC);
}
function fetchRow($qryId = 0) {
$qryId || $qryId = $this-lastQuery;
return mysql_fetch_row($qryId);
}
function fetchAssoc($qryId = 0) {
$qryId || $qryId = $this-lastQuery;
return mysql_fetch_array($qryId, MYSQL_ASSOC);
}
function fetchArray($qryId = 0) {
$qryId || $qryId = $this-lastQuery;
return mysql_fetch_array($qryId, MYSQL_ASSOC);
}
function fetchObject($qryId = 0) {
$qryId || $qryId = $this-lastQuery;
return @mysql_fetch_object($qryId);
}
function result($rst, $row, $column = 0) {
return @mysql_result($rst, $row, $column);
}
function query($sql, $unbuffered = 0) {
if ( $this-debug ) {
$mtime = explode(‘ ‘, microtime());
$stime = $mtime[1] + $mtime[0];
}
$this-lastQuery = @mysql_query($sql, $this-connId);
//$unbuffered ? @mysql_unbuffered_query($sql, $this-connId) :
$this-lastQuery || $this-halt($sql);
if ($this-debug){
$mtime = explode(‘ ‘, microtime());
$etime = $mtime[1] + $mtime[0] – $stime;
$this-qryInfo .= sprintf(“lib%1.5f/b %shr size=1 noshadow\r\n”, $etime, $sql);
$this-qryTime += $etime;
}
$this-qryNum++;
if (strpos($sql, ‘SELECT’) !== false $this-lastQuery) {
$this-openedQueries[(int) $this-lastQuery] = $this-lastQuery;
}
return $this-lastQuery;
}
function dataSeek($rst, $row) {
// $qryId || $qryId = $this-lastQuery;
mysql_data_seek($rst, $row);
}
function debugOn() {$this-debug = true;}
function debugOff() {$this-debug = false;}
function getQueryNum() {return $this-qryNum;}
function affectedRows() {
return @mysql_affected_rows();
}
function numRows($qryId = 0) {
$qryId || $qryId = $this-lastQuery;
return @mysql_num_rows($qryId);
}
function insertId() {
return @mysql_insert_id();
}
function freeResult($qryId) {
$qryId || $qryId = $this-lastQuery;
if (isset($this-openedQueries[(int) $qryId])) {
unset($this-openedQueries[(int) $qryId]);
return @mysql_free_result($qryId);
}
return false;
}
function close() {
if (!$this-connId) {
return false;
}
if ($this-transaction) {
$this-transaction(‘commit’);
}
if ($this-openedQueries){
foreach ($this-openedQueries as $key = $qryId){
$this-freeresult($qryId);
}
}
mysql_close($this-connId);
}
function halt() {
$str = sprintf(“liMYSQL錯誤代碼:%s/li\r\n”, mysql_errno());
$str.= sprintf(“liMYSQL錯誤原因:%s/li\r\n”, mysql_error());
if (func_num_args()) {
$sql = func_get_args();
$str.= sprintf(“liSQL :%s/li\r\n”, $sql[0]);
}
die($str);
}
function debug() {
$str = sprintf(“li共執行(%s)次查詢/li\r\n”, $this-qryNum);
$str.= $this-qryInfo;
$str.= sprintf(“li總用時:b[%1.5f]/b/li\r\n”, $this-qryTime);
return $str;
}
}
自己可以研究一下,這個mysql類很實用的,我一直在用
插入的時候可以這樣寫:
$insert[“name”] = “aaaaaa”;//name就是你的數據庫中的字段名
$insert[“age”] = “20”;
$db-insert(“user”,$insert);
用C語言如何對MySQL數據庫進行操作
有時為了性能,我們會直接用C語言來開發相關的模塊,尤其在我們的web應用中,雖然PHP、JSP等腳本均提供了MySQL的接口,但是顯然直接使用C語言具有更好的安全性和性能,Michael以前用PHP開發的多個項目中就使用了C語言編寫的這類接口,然後再編譯到php裡面,供php腳本直接使用,這方面的話題就不多說了,下面主要說一下在Linux下如何用C語言連接MySQL數據庫,並且讀取裡面的數據返回,同時如何進行編譯。if defined(_WIN32) || defined(_WIN64)為了支持windows平台上的編譯#includewindows.h#endif#includestdio.h#includestdlib.h#includemysql.h我的機器上該文件在/usr/local/include/mysql下定義MySQL數據庫操作的宏,也可以不定義留着後面直接寫進代碼defineSELECT_QUERYselectusernamefromtbb_userwhereuserid=%dintmain(intargc,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_selectuserid\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’tconnecttoengine!\n%s\n\n,mysql_error(mysql));perror();exit(1);}sprintf(qbuf,SELECT_QUERY,atoi(argv[1]));if(mysql_query(sock,qbuf)){fprintf(stderr,Queryfailed(%s)\n,mysql_error(sock));exit(1);}if(!(res=mysql_store_result(sock))){fprintf(stderr,Couldn’tgetresultfrom%s\n,mysql_error(sock));exit(1);}printf(numberoffieldsreturned:%d\n,mysql_num_fields(res));while(row=mysql_fetch_row(res)){printf(Theruserid#%d’susernameis:%s\n,atoi(argv[1]),(((row[0]==NULL)(!strlen(row[0])))?NULL:row[0]));puts(queryok!\n);}mysql_free_result(res);mysql_close(sock);exit(0);return0;為了兼容大部分的編譯器加入此行}編譯的時候,使用下面的命令gcc -o mysql_select ./mysql_select.c -I/usr/local/include/mysql -L/usr/local/lib/mysql -lmysqlclient (-lz) (-lm) 後面兩個選項可選,根據您的環境情況運行的時候,執行下面的命令./mysql_select 1將返回如下結果:numberoffieldsreturned:1Theruserid#1’susernameis:Michaelqueryok!上面的代碼我想大部分都能看明白,不明白的可以參考一下MySQL提供的有關C語言API部分文檔源碼天空,各個函數都有詳細說明,有時間我整理一份常用的API說明出來。
實例講解如何使用C++操作MySQL數據庫類
/* * project: * 通用模塊 ( 用 c++ 處理 mysql 數據庫類,像ADO ) * * description: * * 通過DataBase,RecordSet,Record,Field類,實現對mysql數據庫的操作 * 包括連接、修改、添加、刪除、查詢等等,像ADO一樣操作數據庫,使 * 用方便 * * ( the end of this file have one sample, * welcom to use… ) * * * file:zlb_mysql.h * * author: @ zlb * * time:2005-12-12 * * * –*/ #ifndef ZLB_MYSQL_H #define ZLB_MYSQL_H #include “mysql.h” #include iostream #include vector #include string using namespace std; namespace zlb_mysql{ /* * 字段操作 */ class Field { public : /* 字段名稱 */ vectorstring m_name; /* 字段類型 */ vectorenum_field_types m_type; public : Field(); ~Field(); /* 是否是數字 */ bool IsNum(int num); /* 是否是數字 */ bool IsNum(string num); /* 是否是日期 */ bool IsDate(int num); /* 是否是日期 */ bool IsDate(string num); /* 是否是字符 */ bool IsChar(int num); /* 是否是字符 */ bool IsChar(string num); /* 是否為二進制數據 */ bool IsBlob(int num); /* 是否為二進制數據 */ bool IsBlob(string num); /* 得到指定字段的序號 */ int GetField_NO(string field_name); }; /* * 1 單條記錄 * 2 [int ]操作 [“”]操作 */ class Record { public: /* 結果集 */ vectorstring m_rs; /* 字段信息 佔用4字節的內存 當記錄數很大是回產生性能問題 */ Field *m_field; public : Record(){}; Record(Field* m_f); ~Record(); void SetData(string value); /* [“”]操作 */ string operator[](string s); string operator[](int num); /* null值判斷 */ bool IsNull(int num); bool IsNull(string s); /* 用 value tab value 的形式 返回結果 */ string GetTabText(); }; /* * 1 記錄集合 * 2 [int ]操作 [“”]操作 * 3 表結構操作 * 4 數據的插入修改 */ class RecordSet { private : /* 記錄集 */ vectorRecord m_s; /* 游標位置*/ unsigned long pos; /* 記錄數 */ int m_recordcount; /* 字段數 */ int m_field_num; /* 字段信息 */ Field m_field; MYSQL_RES * res ; MYSQL_FIELD * fd ; MYSQL_ROW row; MYSQL* m_Data ; public : RecordSet(); RecordSet(MYSQL *hSQL); ~RecordSet(); /* 處理返回多行的查詢,返回影響的行數 */ int ExecuteSQL(const char *SQL); /* 得到記錄數目 */ int GetRecordCount(); /* 得到字段數目 */ int GetFieldNum(); /* 向下移動游標 */ long MoveNext(); /* 移動游標 */ long Move(long length); /* 移動游標到開始位置 */ bool MoveFirst(); /* 移動游標到結束位置 */ bool MoveLast(); /* 獲取當前游標位置 */ unsigned long GetCurrentPos()const; /* 獲取當前游標的對應字段數據 */ bool GetCurrentFieldValue(const char * sFieldName,char *sValue); bool GetCurrentFieldValue(const int iFieldNum,char *sValue); /* 獲取游標的對應字段數據 */ bool GetFieldValue(long index,const char * sFieldName,char *sValue); bool GetFieldValue(long index,int iFieldNum,char *sValue); /* 是否到達游標尾部 */ bool IsEof(); /* 返回字段 */ Field* GetField(); /* 返回字段名 */ const char * GetFieldName(int iNum); /* 返回字段類型 */ const int GetFieldType(char * sName); const int GetFieldType(int iNum); /* 返回指定序號的記錄 */ Record operator[](int num); }; /* * 1 負責數據庫的連接關閉 * 2 執行sql 語句(不返回結果) * 3 處理事務 */ class DataBase { public : DataBase(); ~DataBase(); private : /* msyql 連接句柄 */ MYSQL* m_Data; public : /* 返回句柄 */ MYSQL * GetMysql(); /* 連接數據庫 */ int Connect(string host, string user, string passwd, string db, unsigned int port, unsigned long client_flag); /* 關閉數據庫連接 */ void DisConnect(); /* 執行非返回結果查詢 */ int ExecQuery(string sql); /* 測試mysql服務器是否存活 */ int Ping(); /* 關閉mysql 服務器 */ int ShutDown(); /* 主要功能:重新啟動mysql 服務器 */ int ReBoot(); /* * 說明:事務支持InnoDB or BDB表類型 */ /* 主要功能:開始事務 */ int Start_Transaction(); /* 主要功能:提交事務 */ int Commit(); /* 主要功能:回滾事務 */ int Rollback(); /* 得到客戶信息 */ const char * Get_client_info(); /* 主要功能:得到客戶版本信息 */ const unsigned long Get_client_version(); /* 主要功能:得到主機信息 */ const char * Get_host_info(); /* 主要功能:得到服務器信息 */ const char * Get_server_info(); /*主要功能:得到服務器版本信息*/ const unsigned long Get_server_version(); /*主要功能:得到 當前連接的默認字符集*/ const char * Get_character_set_name(); /* 主要功能返回單值查詢 */ char * ExecQueryGetSingValue(string sql); /* 得到系統時間 */ const char * GetSysTime(); /* 建立新數據庫 */ int Create_db(string name); /* 刪除制定的數據庫*/ int Drop_db(string name); }; }; #endif //ZLB_MYSQL_H /* * project: * 通用模塊 ( 用 c++ 處理 mysql 數據庫類,像ADO ) * * description: * * 通過DataBase,RecordSet,Record,Field類,實現對mysql數據庫的操作 * 包括連接、修改、添加、刪除、查詢等等,像ADO一樣操作數據庫,使 * 用方便 * * ( the end of this file have one sample, * welcom to use… ) * * * file:zlb_mysql.cpp * * author: @ zlb * * time:2005-12-12 * * * –*/ #include “stdafx.h” #include “zlb_mysql.h” namespace zlb_mysql{ /* +++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* * 字段操作 */ Field::Field(){} Field::~Field(){} /* * 是否是數字 */ bool Field::IsNum(int num) { if(IS_NUM(m_type[num])) return true; else return false; } /* * 是否是數字 */ bool Field::IsNum(string num) { if(IS_NUM(m_type[GetField_NO(num)])) return true; else return false; } /* * 是否是日期 */ bool Field::IsDate(int num) { if( FIELD_TYPE_DATE == m_type[num] || FIELD_TYPE_DATETIME == m_type[num] ) return true; else return false; } /* 是否是日期 */ bool Field::IsDate(string num) { int temp; temp=GetField_NO(num); if(FIELD_TYPE_DATE == m_type[temp] || FIELD_TYPE_DATETIME == m_type[temp] ) return true; else return false; } /* * 是否是字符 */ bool Field::IsChar(int num) { if(m_type[num]==FIELD_TYPE_STRING || m_type[num]==FIELD_TYPE_VAR_STRING || m_type[num]==FIELD_TYPE_CHAR ) return true; else return false; } /* * 是否是字符 */ bool Field::IsChar(string num) { int temp; temp=this-GetField_NO (num); if(m_type[temp]==FIELD_TYPE_STRING || m_type[temp]==FIELD_TYPE_VAR_STRING || m_type[temp]==FIELD_TYPE_CHAR ) return true; else return false; } /* * 是否為二進制數據 */ bool Field::IsBlob(int num) { if(IS_BLOB(m_type[num])) return true; else return false; } /* * 是否為二進制數據 */ bool Field::IsBlob(string num) { if(IS_BLOB(m_type[GetField_NO(num)])) return true; else return false; } /* * 得到指定字段的序號 */ int Field::GetField_NO(string field_name) { for(unsigned int i=0;im_name.size ();i++) { if(!m_name[i].compare (field_name)) return i; } return -1; } /*—————————————————–*/ /* +++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* * 1 單條記錄 * 2 [int ]操作 [“”]操作 */ Record::Record(Field * m_f) { m_field =m_f; } Record::~Record(){}; void Record::SetData(string value) { m_rs.push_back (value); } /* [“”]操作 */ string Record::operator[](string s) { return m_rs[m_field-GetField_NO(s)]; } string Record::operator[](int num) { return m_rs[num]; } /* null值判斷 */ bool Record::IsNull(int num) { if(“” == m_rs[num].c_str ()) return true; else return false; } bool Record::IsNull(string s) { if(“” == m_rs[m_field-GetField_NO(s)].c_str()) return true; else return false; } /* 主要-功能:用 value tab value 的形式 返回結果 */ string Record::GetTabText() { string temp; for(unsigned int i=0 ;im_rs.size();i++) { temp+=m_rs[i]; if(im_rs.size ()-1) temp+=”\t”; } return temp; } /*—————————————————–*/ /* +++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* * 1 記錄集合 * 2 [int ]操作 [“”]操作 * 3 表結構操作 * 4 數據的插入修改 */ RecordSet::RecordSet() { res = NULL; row = NULL; pos = 0; } RecordSet::RecordSet(MYSQL *hSQL) { res = NULL; row = NULL; m_Data = hSQL; pos = 0; } RecordSet::~RecordSet() { } /* * 處理返回多行的查詢,返回影響的行數 * 成功返回行數,失敗返回-1 */ int RecordSet::ExecuteSQL(const char *SQL) { if ( !mysql_real_query(m_Data,SQL,strlen(SQL))) { //保存查詢結果 res = mysql_store_result(m_Data ); //得到記錄數量 m_recordcount = (int)mysql_num_rows(res) ; //得到字段數量 m_field_num = mysql_num_fields(res) ; for (int x = 0 ; fd = mysql_fetch_field(res); x++) { m_field.m_name.push_back(fd-name); m_field.m_type.push_back(fd-type); } //保存所有數據 while (row = mysql_fetch_row(res)) { Record temp(m_field); for (int k = 0 ; k m_field_num ; k++ ) { if(row[k]==NULL||(!strlen(row[k]))) { temp.SetData (“”); } else { temp.SetData(row[k]); } } //添加新記錄 m_s.push_back (temp); } mysql_free_result(res ) ; return m_s.size(); } return -1; } /* * 向下移動游標 * 返回移動後的游標位置 */ long RecordSet::MoveNext() { return (++pos); } /* 移動游標 */ long RecordSet::Move(long length) { int l = pos + length; if(l0) { pos = 0; return 0; }else { if(l = m_s.size()) { pos = m_s.size()-1; return pos; }else { pos = l; return pos; } } } /* 移動游標到開始位置 */ bool RecordSet::MoveFirst() { pos = 0; return true; } /* 移動游標到結束位置 */ bool RecordSet::MoveLast() { pos = m_s.size()-1; return true; } /* 獲取當前游標位置 */ unsigned long RecordSet::GetCurrentPos()const { return pos; } /* 獲取當前游標的對應字段數據 */ bool RecordSet::GetCurrentFieldValue(const char * sFieldName, char *sValue) { strcpy(sValue,m_s[pos][sFieldName].c_str()); return true; } bool RecordSet::GetCurrentFieldValue(const int iFieldNum,char *sValue) { strcpy(sValue,m_s[pos][iFieldNum].c_str()); return true; } /* 獲取游標的對應字段數據 */ bool RecordSet::GetFieldValue(long index,const char * sFieldName, char *sValue) { strcpy(sValue,m_s[index][sFieldName].c_str()); return true; } bool RecordSet::GetFieldValue(long index,int iFieldNum,char *sValue) { strcpy(sValue,m_s[index][iFieldNum].c_str()); return true; } /* 是否到達游標尾部 */ bool RecordSet::IsEof() { return (pos == m_s.size())?true:false; } /* * 得到記錄數目 */ int RecordSet::GetRecordCount() { return m_recordcount; } /* * 得到字段數目 */ int RecordSet::GetFieldNum() { return m_field_num; } /* * 返回字段 */ Field * RecordSet::GetField() { return m_field; } /* 返回字段名 */ const char * RecordSet::GetFieldName(int iNum) { return m_field.m_name.at(iNum).c_str(); } /* 返回字段類型 */ const int RecordSet::GetFieldType(char * sName) { int i = m_field.GetField_NO(sName); return m_field.m_type.at(i); } const int RecordSet::GetFieldType(int iNum) { return m_field.m_type.at(iNum); } /* * 返回指定序號的記錄 */ Record RecordSet::operator[](int num) { return m_s[num]; } /* ————————————————– */ /* +++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* * 1 負責數據庫的連接關閉 * 2 執行sql 語句(不返回結果) * 3 處理事務 */ DataBase::DataBase() { m_Data = NULL; } DataBase::~DataBase() { if(NULL != m_Data) { DisConnect(); } } /* 返回句柄 */ MYSQL * DataBase::GetMysql() { return m_Data; } /* * 主要功能:連接數據庫 * 參數說明: * 1 host 主機ip地址或者時主機名稱 * 2 user 用戶名 * 3 passwd 密碼 * 4 db 欲連接的數據庫名稱 * 5 port 端口號 * 6 uinx 嵌套字 * 7 client_flag 客戶連接參數 * 返回值: 0成功 -1 失敗 */ int DataBase::Connect(string host, string user, string passwd, string db, unsigned int port, unsigned long client_flag) { if((m_Data = mysql_init(NULL)) mysql_real_connect( m_Data, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(),port , NULL, client_flag)) { //選擇制定的數據庫失敗 if ( mysql_select_db( m_Data, db.c_str () ) 0 ) { mysql_close( m_Data) ; return -1 ; } } else { //初始化mysql結構失敗 mysql_close( m_Data ); return -1 ; } //成功 return 0; } /* * 關閉數據庫連接 */ void DataBase::DisConnect( ) { mysql_close(m_Data) ; } /* * 主要功能: 執行非返回結果查詢 * 參數:sql 待執行的查詢語句 * 返回值; n為成功 表示受到影響的行數 -1 為執行失敗 */ int DataBase::ExecQuery(string sql) { if(!mysql_real_query(m_Data,sql.c_str (),(unsigned long)sql.length()) ) { //得到受影響的行數 return (int)mysql_affected_rows(m_Data) ; } else { //執行查詢失敗 return -1; } } /* * 主要功能:測試mysql服務器是否存活 * 返回值:0 表示成功 -1 失敗 */ int DataBase::Ping() { if(!mysql_ping(m_Data)) return 0; else return -1; } /* * 主要功能:關閉mysql 服務器 * 返回值;0成功 -1 失敗 */ int DataBase::ShutDown() { if(!mysql_shutdown(m_Data,SHUTDOWN_DEFAULT)) return 0; else return -1; } /* * 主要功能:重新啟動mysql 服務器 * 返回值;0表示成功 -1 表示失敗 */ int DataBase::ReBoot() { if(!mysql_reload(m_Data)) return 0; else return -1; } /* * 說明:事務支持InnoDB or BDB表類型 */ /* * 主要功能:開始事務 */ int DataBase::Start_Transaction() { if(!mysql_real_query(m_Data, “START TRANSACTION” , (unsigned long)strlen(“START TRANSACTION”) )) { return 0; } else //執行查詢失敗 return -1; } /* * 主要功能:提交事務 * 返回值:0 表示成功 -1 表示失敗 */ int DataBase::Commit() { if(!mysql_real_query( m_Data, “COMMIT”, (unsigned long)strlen(“COMMIT”) ) ) { return 0; } else //執行查詢失敗 return -1; } /* * 主要功能:回滾事務 * 返回值:0 表示成功 -1 表示失敗 */ int DataBase::Rollback() { if(!mysql_real_query(m_Data, “ROLLBACK”, (unsigned long)strlen(“ROLLBACK”) ) ) return 0; else //執行查詢失敗 return -1; } /* 得到客戶信息 */ const char * DataBase::Get_client_info() { return mysql_get_client_info(); } /*主要功能:得到客戶版本信息*/ const unsigned long DataBase::Get_client_version() { return mysql_get_client_version(); } /* 主要功能:得到主機信息 */ const char * DataBase::Get_host_info() { return mysql_get_host_info(m_Data); } /* 主要功能:得到服務器信息 */ const char * DataBase::Get_server_info() { return mysql_get_server_info( m_Data ); } /* 主要功能:得到服務器版本信息 */ const unsigned long DataBase::Get_server_version() { return mysql_get_server_version(m_Data); } /*主要功能:得到 當前連接的默認字符集*/ const char * DataBase::Get_character_set_name() { return mysql_character_set_name(m_Data); } /* * 主要功能返回單值查詢 */ char * DataBase::ExecQueryGetSingValue(string sql) { MYSQL_RES * res; MYSQL_ROW row ; char *p = NULL; if(!mysql_real_query( m_Data, sql.c_str(),(unsigned long)sql.length())) { //保存查詢結果 res = mysql_store_result( m_Data ) ; row = mysql_fetch_row( res ) ; p = ((row[0]==NULL)||(!strlen(row[0])))?”-1″:row[0]; mysql_free_result( res ) ; } else //執行查詢失敗 p = “-1”; return p; } /* * 得到系統時間 */ const char * DataBase::GetSysTime() { return ExecQueryGetSingValue(“select now()”); } /* * 主要功能:建立新數據庫 * 參數:name 為新數據庫的名稱 * 返回:0成功 -1 失敗 */ int DataBase::Create_db(string name) { string temp ; temp=”CREATE DATABASE “; temp+=name; if(!mysql_real_query( m_Data,temp.c_str () , (unsigned long)temp.length ()) ) return 0; else //執行查詢失敗 return -1; } /* * 主要功能:刪除制定的數據庫 * 參數:name 為欲刪除數據庫的名稱 * 返回:0成功 -1 失敗 */ int DataBase::Drop_db(string name) { string temp ; temp=”DROP DATABASE “; temp+=name; if(!mysql_real_query( m_Data,temp.c_str () , (unsigned long)temp.length ()) ) return 0; else //執行查詢失敗 return -1; } /*—————————————————–*/ }; /* * 使用例子 */ #include “zlb_mysql.h” using namespace std; void main() { zlb_mysql::DataBase zlb; //連接數據庫 if(-1 == zlb.Connect(“localhost”/*本地數據庫,可以是遠程 ip*/, “root”/*用戶名*/,”apple”/*密碼*/, “test”/*數據庫名*/, 0,0/*兩個標誌,mysql文檔有說明,一般為0*/)) { std::cout”connect failed “std::endl; } else { std::cout”connect success”std::endl; } //通過返回的數據庫句柄,建立記錄急,你可以通過返回的這個句柄建立多個記錄急 zlb_mysql::RecordSet rs(zlb.GetMysql()); rs.ExecuteSQL(“select * from testtable”);//這個語句大家都知道是什麼意思了 coutrs.GetRecordCount()/*返回的總的記錄數*/endl; coutrs.GetFieldNum()/*返回的總的字段數*/endl; coutrs[0].GetTabText()/*返回第一條記錄,你也可以rs[1].GetTabText() 如果你有多條記錄, */ endl; /*實現遍列,也可以使用後面的遍列方式*/ for(int i=0;irs.GetRecordCount();++i) { for(int j =0;jrs.GetFieldNum();++j) coutrs[i][j]; coutendl; } zlb_mysql::Field *fd = rs.GetField();/*你可以通過這樣的方式,獲取字段的信息*/ coutfd-GetField_NO(“Password”)/*返回我表裡的 Password 字段的位置,不 是記錄的位置*/ endl; coutrs[0][“Password”]endl;/*輸出第0行第Password列的值*/ coutrs[0][fd-GetField_NO(“Password”)]endl;/*你也可以這樣*/ coutrs.GetFieldName(0)/*獲取字段的名字*/endl; coutrs.GetFieldType(“UserName”)/*獲取字段的類型,是mysql里定義的*/endl; coutrs.GetCurrentPos()/*獲取當前記錄的位置*/endl; char s[50]; rs.GetCurrentFieldValue(1,s);/*獲取當前記錄對應字段的值*/ coutsendl; coutrs.Move(1)endl;/*移動游標,正數往前 負數往後*/ coutrs.GetCurrentPos()endl; rs.GetCurrentFieldValue(1,s); coutsendl; rs.MoveFirst();/*移動游標到最前*/ while(!rs.IsEof()/*判斷是否到達游標尾,實現遍列*/) { rs.GetCurrentFieldValue(“UserName”,s); couts”\t”; rs.GetCurrentFieldValue(“Password”,s); couts”\t
“; rs.MoveNext(); } rs.GetFieldValue(0,”UserName”,s);/*獲取指定行 的記錄值*/ couts”\t”; rs.GetFieldValue(0,”Password”,s); couts”\t
“; }
jdbc連接數據庫的代碼問題jdbc連接mysql數據庫
用這個類吧.好的話,給我加加分.
import java.sql.*;
/**
* @功能: 一個JDBC的本地化API連接類,封裝了數據操作方法,只用傳一個SQL語句即可
* @作者: 李開歡
* @日期: 2007/
*/
public class ConnectionDemo {
/*
* 這裡可以將常量全部放入另一個類中,以方便修改
*/
private static Connection conn;
private static Statement ps;
private static ResultSet rs;
private static final String DRIVER = “com.microsoft.jdbc.sqlserver.SQLServerDriver”;
private static final String URL = “jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb”;
private static final String USER =”sa”;
private static final String PASS = “sa”;
public ConnectionDemo() {
// TODO Auto-generated constructor stub
ConnectionDemo.getConnection();
}
public static Connection getConnection(){
System.out.println(“連接中…”);
try {
Class.forName(ConnectionDemo.DRIVER);
conn = DriverManager.getConnection(ConnectionDemo.URL, ConnectionDemo.USER, ConnectionDemo.PASS);
System.out.println(“成功連接”);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static Statement getStatement(String sql){
System.out.println(“執行SQL語句中…”);
try {
ps = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
if(sql.substring(0, 6).equals(“select”)){
rs = ps.executeQuery(sql);
System.out.println(“執行完查詢操作,結果已返回ResultSet集合”);
}else if(sql.substring(0, 6).equals(“delete”)){
ps.executeUpdate(sql);
System.out.println(“已執行完畢刪除操作”);
}else if(sql.substring(0, 6).equals(“insert”)){
ps.executeUpdate(sql);
System.out.println(“已執行完畢增加操作”);
}else{
ps.executeUpdate(sql);
System.out.println(“已執行完畢更新操作”);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ps;
}
public static ResultSet getResultSet(){
System.out.println(“查詢結果為:”);
return rs;
}
public static void closeConnection(){
System.out.println(“關閉連接中…”);
try {
if (rs != null) {
rs.close();
System.out.println(“已關閉ResultSet”);
}
if (ps != null) {
ps.close();
System.out.println(“已關閉Statement”);
}
if (conn != null) {
conn.close();
System.out.println(“已關閉Connection”);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConnectionDemo.getConnection();
String sql = “delete from type where id = 1”;
ConnectionDemo.getStatement(sql);
String sql2 = “insert into type values(1,’教學設備’)”;
ConnectionDemo.getStatement(sql2);
String sql1 = “select * from type”;
ConnectionDemo.getStatement(sql1);
ResultSet rs = ConnectionDemo.getResultSet();
System.out.println(“編號 “+”類 型”);
try {
while(rs.next()){
System.out.print(” “+rs.getInt(1)+” “);
System.out.println(rs.getString(2));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ConnectionDemo.closeConnection();
}
}
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;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/258221.html