【转载】Ue4连接MySQL(上)

原文地址:点击打开链接

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

9KGameStudioMysql教程地址:https://forums.unrealengine.com/showthread.php?65944-c-Mysql-database-error&highlight=mysql

 

写在教程之前:

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

此文是9KGameStudioMysql教程的中文重写版,里面会写入一些个人体会,当然本人也是个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

3MySQL 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("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、到你的项目中的2CS文件中加入OutExtraModuleNames.AddRange(new string[]{ "MySQLSupport" });

 

MyProject.Target.cs

MyProjectEditor.Target.cs

 

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

 

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

二、包含Mysql连接文件

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

包含目录:对应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

#include

#include"HideWindowsPlatformTypes.h"

 

#pragmacomment(lib, "libmysql.lib")

 

AMyGameMode::AMyGameMode(constFObjectInitializer& ObjectInitializer)

: Super(ObjectInitializer)

{

    DefaultPawnClass = AMyCharacter::StaticClass();

 

   

    static ConstructorHelpers::FClassFinderPlayerPawnObject(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"EngineMinimal.h"改成#include "Engine.h"

 

#include

#include

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

#include"AllowWindowsPlatformTypes.h"

#include"HideWindowsPlatformTypes.h"

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

 

PS:关于使用第三方库的另一盘文章(中文)https://wiki.unrealengine.com/UE4WEB服务器交互(json)

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

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

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

编译的错误:

错误 7   error : Failed to produce item:C:\Users\creaform\Documents\UnrealProjects\ThirdPerson\Binaries\Win64\UE4Editor-ThirdPerson.dll   C:\Users\creaform\Documents\UnrealProjects\ThirdPerson\Intermediate\ProjectFiles\ERROR    ThirdPerson

错误 6   error LNK1120: 4 个无法解析的外部命令  C:\Users\creaform\Documents\UnrealProjects\ThirdPerson\Binaries\Win64\UE4Editor-ThirdPerson.dll   ThirdPerson

错误 5   error LNK2019: 无法解析的外部符号 mysql_close,该符号在函数 "public: virtual void __cdeclAThirdPersonGameMode::BeginPlay(void)" (?BeginPlay@AThirdPersonGameMode@@UEAAXXZ)中被引用    C:\Users\creaform\Documents\UnrealProjects\ThirdPerson\Intermediate\ProjectFiles\ThirdPersonGameMode.cpp.obj  ThirdPerson

错误 4   error LNK2019: 无法解析的外部符号mysql_get_server_version,该符号在函数 "public: virtual void __cdeclAThirdPersonGameMode::BeginPlay(void)"(?BeginPlay@AThirdPersonGameMode@@UEAAXXZ) 中被引用    C:\Users\creaform\Documents\UnrealProjects\ThirdPerson\Intermediate\ProjectFiles\ThirdPersonGameMode.cpp.obj  ThirdPerson

错误 2   error LNK2019: 无法解析的外部符号 mysql_init,该符号在函数 "public: virtual void __cdeclAThirdPersonGameMode::BeginPlay(void)"(?BeginPlay@AThirdPersonGameMode@@UEAAXXZ) 中被引用    C:\Users\creaform\Documents\UnrealProjects\ThirdPerson\Intermediate\ProjectFiles\ThirdPersonGameMode.cpp.obj  ThirdPerson

错误 3   error LNK2019: 无法解析的外部符号mysql_real_connect,该符号在函数 "public: virtual void __cdeclAThirdPersonGameMode::BeginPlay(void)"(?BeginPlay@AThirdPersonGameMode@@UEAAXXZ) 中被引用    C:\Users\creaform\Documents\UnrealProjects\ThirdPerson\Intermediate\ProjectFiles\ThirdPersonGameMode.cpp.obj  ThirdPerson

错误 8   error MSB3073: 命令“D:\unreal4\UnrealEngine-release\UnrealEngine-release\Engine\Build\BatchFiles\Build.batThirdPersonEditor Win64 Development "C:\Users\creaform\Documents\UnrealProjects\ThirdPerson\ThirdPerson.uproject"”已退出,代码为 -1    C:\Program Files(x86)\MSBuild\Microsoft.Cpp\v4.0\V120\Microsoft.MakeFile.Targets   38  5    ThirdPerson

警告 1   未能找到引用的组件“RPCUtility”。 iPhonePackager



你可能感兴趣的:(Ue4)