使用Ue4连接Mysql数据库




首先感谢一下官方论坛的9KGameStudio 以及A先生,没有你们就没有此文。

9KGameStudio的Mysql教程地址:[c++] Mysql database error - C++ Gameplay Programming - Unreal Engine Forums

写在教程之前:

Ue4使用Module这个东西来管理第三方的库,(包括你的工程)。我认为这个机制是Ue4程序员必须掌握的东西,不然你在扩展UE4库的路上将会寸步难行。

此文是9KGameStudio的Mysql教程的中文重写版,里面会写入一些个人体会,当然本人也是个UE4 C++菜鸟,有错的地方还请见谅。

教程开始:

一、建立你自己的mysqlModule。

1、在你的项目文件夹下建立一个名为ThirdParty的文件夹

MyProject

        Binaries
        Build
        Config
        Content
        Intermediate
       Saved
       Source
          ThirdParty
       MyProject.sln
       MyProject.uproject

2、之后将Mysql连接文件放入这个文件夹,本教程中用的是 MySQL Connector.C6.1。

ThirdParty

  MySQL Connector.C 6.1

  include
  lib

3、将MySQL Connector.C6.1文件夹中的空格去掉,改成MySQLConnector.C6.1。

4、按照一下结构建立目录:

Source(你工程中的Source目录)

  MyProject (Source目录下的,你的CPP,H文件放置目录)
  MySQLSupport (在Source下新建文件夹,并且命名MySQLSupport,注意大小写!)

       Public(在MySQLSupport目录下新建文件夹)

             MySQLSupport.h(在Public目录下,使用记事本文件新建再改名)

       Private(在MySQLSupport目录下新建文件夹)

             MySQLSupport.cpp(在Private目录下,使用记事本文件新建再改名)
             MySQLSupportPrivatePCH.h(在Private目录下,使用记事本文件新建改名)

       MySQLSupport.Build.cs(在MySQLSupport目录下,使用记事本文件新建再改名)

5、为新建的文件编写代码:

MySQLSupport.h



#pragma once

 

#include "ModuleManager.h"

 

class IMySQLSupport : publicIModuleInterface

{

public:

 

         staticinline IMySQLSupport& Get()

         {

                 returnFModuleManager::LoadModuleChecked<IMySQLSupport>("MySQLSupport");

         }

 

         staticinline bool IsAvailable()

         {

                 returnFModuleManager::Get().IsModuleLoaded("MySQLSupport");

         }

};


MySQLSupport.cpp



#include "MySQLSupportPrivatePCH.h"#include "MySQLSupport.h" class FMySQLSupport : public IMySQLSupport{          virtual void StartupModule() override;          virtual void ShutdownModule() override;}; IMPLEMENT_MODULE(FMySQLSupport, MySQLSupport) void FMySQLSupport::StartupModule(){ } void FMySQLSupport::ShutdownModule(){ }

MySQLSupportPrivatePCH.h



#pragma once #include "Engine.h"

MySQLSupport.Build.cs



using UnrealBuildTool;using System.IO; public class MySQLSupport : ModuleRules{    public MySQLSupport(TargetInfo Target)    {         PublicDependencyModuleNames.AddRange(            new string] {                "Core",                "CoreUObject",                "Engine"            });         string ModulePath = Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name));        // gets the directory path of this module        string ThirdPartyPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/"));                // gets the ThirdParty folder directory path        string MySQLConnectorPath = ThirdPartyPath + "MySQL Connector.C 6.1/";                                  // gets the MySQL Connector.C 6.1 folder path        string MySQLConnectorLibraryPath = MySQLConnectorPath + "lib/";                                         // gets the path of the lib folder        string MySQLConnectorIncludePath = MySQLConnectorPath + "include/";                                     // gets the path of the include folder        string MySQLConnectorImportLibraryName = Path.Combine(MySQLConnectorLibraryPath, "libmysql.lib");       // gets the file path and name of the libmysql.lib static import library        string MySQLConnectorDLLName = Path.Combine(MySQLConnectorLibraryPath, "libmysql.dll");                 // gets the file path and name of libmysql.dll         if (!File.Exists(MySQLConnectorImportLibraryName))                                                      // check to ensure the static import lib can be located, or else we'll be in trouble        {            throw new BuildException(string.Format("{0} could not be found.", MySQLConnectorImportLibraryName));        // log an error message explaining what went wrong if not found        }         if (!File.Exists(MySQLConnectorDLLName))                                                                // check to make sure the dll can be located or else we'll be in trouble        {            throw new BuildException(string.Format("{0} could not be found.", MySQLConnectorDLLName));          // log an error message explaining what went wrong if not found        }         PrivateIncludePaths.Add(MySQLConnectorIncludePath);                                                     // add the "include" folder to our dependencies. I've chosen PrivateIncludePaths since I hide the mysql headers from external code        PublicLibraryPaths.Add(MySQLConnectorLibraryPath);                                                      // add the "lib" folder to our dependencies        PublicAdditionalLibraries.Add(MySQLConnectorImportLibraryName);                                         // add libmysql.lib static import library as a dependency        PublicDelayLoadDLLs.Add(MySQLConnectorDLLName);                                                         // add libmysql.dll as a dll    }}


6、到你的项目中的2个CS文件中加入OutExtraModuleNames.AddRange(new string]{ “MySQLSupport” });

MyProject.Target.cs

MyProjectEditor.Target.cs

这里有一个百思不得其解的地方,A先生的项目需要经过这一步才能正常编译。本人家中电脑不加也可以正常编译。

注意:你需要把MySQLConnector.C 6.1 中的空格去掉

二、包含Mysql连接文件

在你的项目上右键-属性-VC++目录-包含目录与库目录中填入,刚才建立的ThirdParty中的连接文件中include与lib目录。

包含目录:对应include

C:\Users\creaform\Documents\Unreal Projects\ThirdPerson\ThirdParty\MySQLConnector.C6.1\include;$(IncludePath)

库目录:对应lib

C:\Users\creaform\Documents\Unreal Projects\ThirdPerson\ThirdParty\MySQLConnector.C6.1\lib;$(LibraryPath)

三、使用代码连接Mysql

这里你贴一段A先生的代码。他是把代码写在GameMode中的

MyGameMode.h



#pragmaonce

 

#include"GameFramework/GameMode.h"

#include"MyGameMode.generated.h"

 

/**

 *

 */

UCLASS()

classFSGAME_API AMyGameMode : public AGameMode

{

    GENERATED_UCLASS_BODY()

    virtual void BeginPlay() OVERRIDE;

};

 


MyGameMode.cpp



#include"FSGame.h"

#include"MyGameMode.h"

#include"MyCharacter.h"

#include"MySQLSupport/Public/MySQLSupport.h"

#include"AllowWindowsPlatformTypes.h"

#include<winsock2.h>

#include<mysql.h>

#include"HideWindowsPlatformTypes.h"

 

#pragmacomment(lib, "libmysql.lib")

 

AMyGameMode::AMyGameMode(constFObjectInitializer& ObjectInitializer)

: Super(ObjectInitializer)

{

    DefaultPawnClass = AMyCharacter::StaticClass();

 

   

    static ConstructorHelpers::FClassFinder<APawn>PlayerPawnObject(TEXT("/Game/StarterContent/Character/MyChatacter_Blueprint"));

 

    if (PlayerPawnObject.Class != NULL){

        DefaultPawnClass = PlayerPawnObject.Class;

    }

}

 

voidAMyGameMode::BeginPlay()

{

    if (GEngine) {

        MYSQL* conn;

        conn = mysql_init(NULL);

        mysql_real_connect(conn, "127.0.0.1","root", "123456", "test", 3306, NULL, 0);

        int32 version = mysql_get_server_version(conn);

        mysql_close(conn);

        FString version_str;

       

        version_str = FString::FormatAsNumber(version);

        GEngine->AddOnScreenDebugMessage(-1, 10.f,FColor(255, 0, 0), TEXT("正在使用MyGameMode"));

        GEngine->AddOnScreenDebugMessage(-1, 10.f,FColor(255, 0, 0), FString(TEXT("当前正在使用的mysql版本为"))+version_str);

    }

}



当然代码不能照搬照抄,你需要求改修改代码中的函数名,等一些东西,因为用到GEngine,所以需要到你的项目头文件中把#include"EngineMini.h"改成#include “Engine.h”

#include<winsock2.h>

#include<mysql.h>

这两个头文件用于mysql的依赖项

#include"AllowWindowsPlatformTypes.h"

#include"HideWindowsPlatformTypes.h"

这两个头文件使得MFC的一些变量可以正常使用。

PS:关于使用第三方库的另一盘文章(中文)A new, community-hosted Unreal Engine Wiki - Announcements and Releases - Unreal Engine Forums

我使用虚拟机测试过可以远程连接Mysql数据库,当然之前需要设置一下让Mysql允许别的Ip连接。

我是使用MySQL Workbench 6.3 CE,登陆数据库,之后在Users and Privileges 选项中把用户的IP改成%。

本人家中电脑已经成功2次了,但是另一台电脑却总是编译失败。不知道为什么?

好,我让技术人员来看看

编译失败是我机子的原因

啊,机器什么原因啊,dll没有找到还是别的?

请教一下RulesCompiler是哪里来的。
并没有找到UE4里有这个东西,使用版本4.12

好文 果断学习!!! 感谢

支持一下,在如此冷清的中文板块能看到技术文章.

666666我喜欢 收藏学习之

打包失败

非常感谢楼主的技术指导。我按照这个流程做完以后,VS和UE4里测试都正常运作。但是无法打包。打包的时候始终找不到mysql.h这个文件。

日志报错:
UATHelper: 打包 (Windows (64位)): UnrealBuildTool: e: est\ue4 est\cccc13\source\cccc13\MySQLTest.h(5): fatal error C1083: �޷��?����ļ�: ��mysql.h��: No such file or directory
UATHelper: 打包 (Windows (64位)): UnrealBuildTool: e: est\ue4 est\cccc13\source\cccc13\MySQLTest.h(5): fatal error C1083: �޷��?����ļ�: ��mysql.h��: No such file or directory

我觉得可能是ThirdParty这个模块始终没有被项目识别,我不知道该怎么办。还请指点一下,非常感谢

好文,收藏!!!!!

A先生是anhanjinj么:rolleyes:,我之前也写过一个UE4 mysql插件哦