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

发布时间:2022-11-14

本文目录一览:

  1. 请问哪位会写php连接mysql数据库的代码。
  2. 用C语言如何对MySQL数据库进行操作
  3. 实例讲解如何使用C++操作MySQL数据库类
  4. jdbc连接数据库的代码问题jdbc连接mysql数据库
  5. [c语言怎么连接mysql数据库 代码](#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);
        $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) {
        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 &nbsp; &nbsp;:%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 数据库,并且读取里面的数据返回,同时如何进行编译。

#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
#define SELECT_QUERY "select username from tbb_user where userid=%d"
int main(int argc, char **argv) {
    MYSQL mysql, *sock;
    MYSQL_RES *res;
    MYSQL_FIELD *fd;
    MYSQL_ROW row;
    char qbuf[160];
    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("The 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
The userid#1's username is: Michael
query ok!

上面的代码我想大部分都能看明白,不明白的可以参考一下 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:
        /* 字段名称 */
        vector<string> m_name;
        /* 字段类型 */
        vector<enum_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 [""]操作
     */
    class Record {
    public:
        /* 结果集 */
        vector<string> 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 [""]操作
     * 3 表结构操作
     * 4 数据的插入修改
     */
    class RecordSet {
    private:
        /* 记录集 */
        vector<Record> 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);
    };
} // namespace zlb_mysql
#endif // ZLB_MYSQL_H

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) {
            e.printStackTrace();
        } catch (SQLException e) {
            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) {
            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) {
            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;
}