mysql connectorc++ 基础教程(一)

一:介绍

默认已经装好了 connector c++,未装好请转mysql connector c++ 安装
默认已初步了解sql语法
默认写给N多天后的自己,比较基础
内容是从官网上学习的,简化了步骤—官方教程
源码基本复制就能跑
特别提醒:编译时,需要加上 -lmysqlcppconn

二:增删改查
#include <cppconn/driver.h>
#include <cppconn/connection.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/metadata.h>
#include <cppconn/resultset_metadata.h>
#include <cppconn/exception.h>
#include <cppconn/warning.h>

#define DBHOST "tcp://127.0.0.1:3306"
#define USER "root"
#define PASSWORD "123456"
#define DATABASE "sys"

using namespace std;
using namespace sql;


int main()
{
     try
    {
        //连接数据库
        Driver *driver = get_driver_instance();
        Connection *conn = driver->connect(DBHOST, USER, PASSWORD);

        Statement *stm;


        if(!conn->isValid()){
            cout<<"数据库连接无效"<<endl;
            return 0;
        }else
            cout<<"数据库连接成功"<<endl;
        //创建 test 表,添加数据
        stm = conn->createStatement();
        stm->execute("use " DATABASE);
        stm->execute("DROP TABLE IF EXISTS test");
        stm->execute("CREATE TABLE test(id INT,lable CHAR(1))");
        stm->execute("INSERT INTO test(id,lable) VALUES(6,'A')");
        stm->execute("INSERT INTO test(id,lable) VALUES(3,'A')");
        stm->execute("INSERT INTO test(id,lable) VALUES(2,'A')");

        //升序查询
        ResultSet *rss;
        rss = stm->executeQuery("SELECT id,lable FROM test ORDER BY id ASC");
        while (rss->next())
        {
            /* code */

            int id = rss->getInt(1);
            string lable = rss->getString("lable");

            cout << "id:" << id << ","
                 << "lable:" << lable << endl;
        }


        //删除
        stm->execute("DELETE FROM test WHERE id=3");

        //改
        stm->execute("UPDATE test SET lable='B' WHERE id=2");

        delete stm;
        delete conn;
        delete rss;
    
    }
    catch (const SQLException &sqle)
    {
        cout << "# ERR: SQLException in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << endl;
        std::cerr << "sql errcode:" << sqle.getErrorCode() << ",state:" << sqle.getSQLState() << ",what:" << sqle.what() << endl;
    }

    return 0;
}
三:预编译语句(PreparedStatement )

使用条件(个人理解):同样的语句在多次执行时(只有变量不同,其余都相同,且将要执行多次)

#include <cppconn/driver.h>
#include <cppconn/connection.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/metadata.h>
#include <cppconn/resultset_metadata.h>
#include <cppconn/exception.h>
#include <cppconn/warning.h>

#define DBHOST "tcp://127.0.0.1:3306"
#define USER "root"
#define PASSWORD "123456"
#define DATABASE "sys"

using namespace std;
using namespace sql;


int main()
{
    try
    {
        /* code */
        Driver *driver = get_driver_instance();
        Connection *conn = driver->connect(DBHOST, USER, PASSWORD);
        Statement *stm;
        
        ResultSet *rss;

        stm = conn->createStatement();
        stm->execute("use " DATABASE);
        stm->execute("DROP TABLE IF EXISTS test");
        stm->execute("CREATE TABLE test(id INT,lable CHAR(1))");

        //预编译语句
        PreparedStatement *pstm;
        pstm = conn->prepareStatement("INSERT INTO test(id,lable) VALUES(?,?)");
        pstm->setInt(1, 3);
        pstm->setString(2, "c");
        pstm->execute();
        pstm->setInt(1, 4);
        pstm->setString(2, "d");
        pstm->execute();
        pstm->setInt(1, 1);
        pstm->setString(2, "b");
        pstm->execute();

        rss = stm->executeQuery("SELECT id,lable FROM test ORDER BY id ASC");

        while (rss->next())
        {
            /* code */

            int id = rss->getInt(1);
            string lable = rss->getString("lable");

            cout << "id:" << id << ","
                 << "lable:" << lable << endl;
        }

        delete stm;
        delete conn;
        delete rss;
        delete pstm;
    }
    catch (const SQLException &sqle)
    {
        cout << "# ERR: SQLException in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << endl;
        std::cerr << "sql errcode:" << sqle.getErrorCode() << ",state:" << sqle.getSQLState() << ",what:" << sqle.what() << endl;
    }

    return 0;
}
四:过程函数

因为是学的官方教程,固依赖了官方的数据库,下载地址
在这里插入图片描述

下面代码分为有返回值和没有返回值的函数,都有注释,结果都有打印,执行完代码后可以看到数据库增加了许多函数
在这里插入图片描述
源码

#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
/* uncomment for applications that use vectors */
/*#include <vector>*/

#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

#define EXAMPLE_HOST "tcp://127.0.0.1:3306"
#define EXAMPLE_USER "root"
#define EXAMPLE_PASS "123456"
#define EXAMPLE_DB "world"

using namespace std;
//没有返回值的语句
const string procedure_noresult = "CREATE PROCEDURE add_country (IN country_code CHAR(3),IN country_name CHAR(52),IN continent_name CHAR(30))\n"
                                  "BEGIN\n"
                                  "INSERT INTO country(Code, Name, Continent)\n"
                                  "VALUES (country_code, country_name, continent_name);\n"
                                  "END;";
//有返回值的语句
const string procedure_result = "CREATE PROCEDURE get_pop (IN country_name CHAR(52),OUT country_pop BIGINT)\n"
                                "BEGIN\n"
                                "SELECT Population INTO country_pop FROM country\n"
                                "WHERE Name = country_name;\n"
                                "END;";
//有返回值的语句
const string procedure_result1 = "CREATE PROCEDURE get_pop_continent (IN continent_name CHAR(30),OUT continent_pop BIGINT)\n"
                                 "BEGIN\n"
                                 "SELECT SUM(Population) INTO continent_pop FROM country\n"
                                 "WHERE Continent = continent_name;\n"
                                 "END;\n";
//有返回值的语句
const string procedure_result2 = "CREATE PROCEDURE get_pop_world (OUT world_pop BIGINT)\n"
                                 "BEGIN\n"
                                 "SELECT SUM(Population) INTO world_pop FROM country;\n"
                                 "END;\n";
//有返回值的语句
const string procedure_result3 = "CREATE PROCEDURE get_data ()\n"
                                 "BEGIN\n"
                                 "SELECT Code, Name, Population, Continent FROM country\n"
                                 "WHERE Continent = 'Oceania' AND Population < 10000;\n"
                                 "SELECT Code, Name, Population, Continent FROM country\n"
                                 "WHERE Continent = 'Europe' AND Population < 10000;\n"
                                 "SELECT Code, Name, Population, Continent FROM country\n"
                                 "WHERE Continent = 'North America' AND Population < 10000;\n"
                                 "END;";
void testNoResult();
void testResult();
void testResult1();

int main(int argc, const char **argv)
{

  cout << "Connector/C++ tutorial framework..." << endl;
  cout << endl;



  try
  {

    /* INSERT TUTORIAL CODE HERE! */
    //testNoResult();
    //testResult();
    testResult1();
  }
  catch (sql::SQLException &e)
  {
    /*
      MySQL Connector/C++ throws three different exceptions:

      - sql::MethodNotImplementedException (derived from sql::SQLException)
      - sql::InvalidArgumentException (derived from sql::SQLException)
      - sql::SQLException (derived from std::runtime_error)
    */
    cout << "# ERR: SQLException in " << __FILE__;
    cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
    /* what() (derived from std::runtime_error) fetches error message */
    cout << "# ERR: " << e.what();
    cout << " (MySQL error code: " << e.getErrorCode();
    cout << ", SQLState: " << e.getSQLState() << " )" << endl;

    return EXIT_FAILURE;
  }

  cout << "Done." << endl;
  return EXIT_SUCCESS;
}

void testResult()
{

  sql::Driver *driver = get_driver_instance();
  std::auto_ptr<sql::Connection> con(driver->connect(EXAMPLE_HOST, EXAMPLE_USER, EXAMPLE_PASS));
  con->setSchema(EXAMPLE_DB);
  std::auto_ptr<sql::Statement> stmt(con->createStatement());

  stmt->execute("DROP PROCEDURE IF EXISTS get_pop");
  stmt->execute(procedure_result);
  stmt->execute("DROP PROCEDURE IF EXISTS get_pop_continent");
  stmt->execute(procedure_result1);
  stmt->execute("DROP PROCEDURE IF EXISTS get_pop_world");
  stmt->execute(procedure_result2);


  stmt->execute("CALL get_pop('Uganda', @pop)");
  std::auto_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT @pop AS _reply"));
  while (res->next())
    cout << "Population of Uganda: " << res->getString("_reply") << endl;

  stmt->execute("CALL get_pop_continent('Asia', @pop)");

  res.reset(stmt->executeQuery("SELECT @pop AS _reply"));
  while (res->next())
    cout << "Population of Asia: " << res->getString("_reply") << endl;

  stmt->execute("CALL get_pop_world(@pop)");

  res.reset(stmt->executeQuery("SELECT @pop AS _reply"));
  while (res->next())
    cout << "Population of World: " << res->getString("_reply") << endl;
}

void testNoResult()
{

  sql::Driver *driver = get_driver_instance();
  std::auto_ptr<sql::Connection> con(driver->connect(EXAMPLE_HOST, EXAMPLE_USER, EXAMPLE_PASS));
  con->setSchema(EXAMPLE_DB);
  std::auto_ptr<sql::Statement> stmt(con->createStatement());

  // We need not check the return value explicitly. If it indicates
  // an error, Connector/C++ generates an exception.

  stmt->execute("DROP PROCEDURE IF EXISTS add_country");
  stmt->execute(procedure_noresult);
  stmt->execute("CALL add_country('ATL', 'Atlantis', 'North America')");
}

void testResult1()
{

  sql::Driver *driver = get_driver_instance();
  std::auto_ptr<sql::Connection> con(driver->connect(EXAMPLE_HOST, EXAMPLE_USER, EXAMPLE_PASS));
  con->setSchema(EXAMPLE_DB);
  std::auto_ptr<sql::Statement> stmt(con->createStatement());

  stmt->execute("DROP PROCEDURE IF EXISTS get_data");
  stmt->execute(procedure_result3);
  stmt->execute("CALL get_data()");
  std::auto_ptr<sql::ResultSet> res;
  do
  {
    res.reset(stmt->getResultSet());
    while (res->next())
    {
      cout << "Name: " << res->getString("Name")
           << " Population: " << res->getInt("Population")
           << endl;
    }
  } while (stmt->getMoreResults());
}
  • 5
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dai1396734

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值