首页 > 编程知识 正文

mysql数据库操作类代码(mysql基本代码)

时间:2023-12-20 12:40:57 阅读:318262 作者:WFFI

本文目录一览:

请问哪位会写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 noshadowrn", $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/lirn", mysql_errno());

$str.= sprintf("liMYSQL错误原因:%s/lirn", mysql_error());

if (func_num_args()) {

$sql = func_get_args();

$str.= sprintf("liSQL    :%s/lirn", $sql[0]);

}

die($str);

}

function debug() {

$str = sprintf("li共执行(%s)次查询/lirn", $this-qryNum);

$str.= $this-qryInfo;

$str.= sprintf("li总用时:b[%1.5f]/b/lirn", $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_selectuseridnn);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%snn,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%sn,mysql_error(sock));exit(1);}printf(numberoffieldsreturned:%dn,mysql_num_fields(res));while(row=mysql_fetch_row(res)){printf(Theruserid#%d'susernameis:%sn,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:WAMPBINMYSQLMYSQL5.5.8LIB 路径

//在工程设置-》链接》库模块中添加 libmysql.lib

#include stdio.h

#include time.h

#include string.h

#include winsock.h

#include "E:wampbinmysqlmysql5.5.8includemysql.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,"%sn",mysql_error(conn));

exit(1);

}

if(mysql_query(conn,sql)){

fprintf(stderr,"%sn",mysql_error(conn));

exit(1);

}

res=mysql_use_result(conn);

while((row = mysql_fetch_row(res))!=NULL){

printf("%sn",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%snn",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 %sn", mysql_error(handle));

}

printf("number of fields returned: %dn",mysql_num_fields(result));

//读取结果集的内容

while (row = mysql_fetch_row(result)) {

printf("table: %sn",(((row[0]==NULL)(!strlen(row[0]))) ? "NULL" : row[0]) ) ;

}

//释放结果集

mysql_free_result(result);

//关闭数据库连接

mysql_close(handle);

system("PAUSE");

//为了兼容大部分的编译器加入此行

return 0;

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。