UE 4学習ノート--MySQLデータベース(C++)への接続


UE 4ラーニングノート--MySQLデータベースに接続する
個人的には水っぽい人なので、学校でちゃんとプログラムを勉強していなかったり、本業を間違えずにモデリングをしたりしていましたが、今は美術もプログラムもダメなのですが….
私は何人かの大物のブログについて、後で忘れないように自分の問題を記録しました.
大物のリンクは以下の通りです.
https://blog.csdn.net/jack0596_cn/article/details/52387890.
https://blog.csdn.net/boonti/article/details/84255014.
UE 4 MySQLデータベースへの接続手順
  • まずMySQLの接続ファイルMySQL Connectorを入手しました.C 6.1(C:Program FilesMySQLファイルの下で、自分のプログラムに必要なのは32ビットのライブラリか64ビットのライブラリかをよく見てください)
  • その後、プロジェクトフォルダの下にフォルダThirdPartyを新規作成し、接続ファイルをThirdPartyフォルダの下にコピーし、接続ファイルのファイル名のスペースをすべて
  • 削除する
  • libフォルダの下のdllファイルをプロジェクトフォルダの下のBinariesフォルダ
  • に置く
  • 従来のC++サードパーティ製ライブラリを追加する方法は幻にはあまり適用されず、一連の問題が発生する可能性があるため、プラグインモジュールにある.build.csの下に以下のコード
  • を追加
    using UnrealBuildTool;
    using System.IO;
    public class MySQLUtility : ModuleRules
    {
       public MySQLUtility(ReadOnlyTargetRules Target) : base(Target)
       {
       	PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
       	
    
    
       	PublicIncludePaths.AddRange(
       		new string[] {
       			// ... add public include paths required here ...
       		}
       		);
       			
       	
       	PrivateIncludePaths.AddRange(
       		new string[] {
       			// ... add other private include paths required here ...
       		}
       		);
       		
       	
       	PublicDependencyModuleNames.AddRange(
       		new string[]
       		{
       			"Core",
       			// ... add other public dependencies that you statically link with here ...
       		}
       		);
       		
       	
       	PrivateDependencyModuleNames.AddRange(
       		new string[]
       		{
       			"CoreUObject",
       			"Engine",
       			"Slate",
       			"SlateCore",
                   //"HeadMountedDisplay",
       			// ... add private dependencies that you statically link with here ...	
       		}
       		);
       	
       	
       	DynamicallyLoadedModuleNames.AddRange(
       		new string[]
       		{
       			// ... add any modules that your module loads dynamically here ...
       		}
       		);
    //       
           string ModulePath = ModuleDirectory; //   .build.cs     
           string ThirdPartyPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/"));//           。
           string MySQLConnectorLibraryPath = ThirdPartyPath + "MySQLConnectorC8/lib64/";//         。
           string MySQLConnectorIncludePath = ThirdPartyPath + "MySQLConnectorC8/include/jdbc/";//            。
           string MySQLConnectorImportLibraryName = Path.Combine(MySQLConnectorLibraryPath, "vs14/mysqlcppconn.lib");//              。
           string MySQLConnectorDLLName = Path.Combine(MySQLConnectorLibraryPath, "mysqlcppconn-7-vs14.dll");//               。
    
           if (!File.Exists(MySQLConnectorImportLibraryName))
           {
               throw new BuildException(string.Format("{0} could not be found.", MySQLConnectorImportLibraryName));//       ,     !
           }
    
           if (!File.Exists(MySQLConnectorDLLName))
           {
               throw new BuildException(string.Format("{0} could not be found.", MySQLConnectorDLLName));
           }
    
           PublicIncludePaths.Add(MySQLConnectorIncludePath);//            。
           PublicLibraryPaths.Add(MySQLConnectorLibraryPath);//             。
           PublicAdditionalLibraries.Add(MySQLConnectorImportLibraryName);//           。
           //PublicDelayLoadDLLs.Add(MySQLConnectorDLLName);
           bEnableUndefinedIdentifierWarnings = false;
       }
    }
    
    
  • 工事に対応する.build.csのファイルにb E n a b l eUndefinedIdentifierWarnings=falseを追加します.「○○」をプリプロセッサマクロとして定義、「#if/#elif」を「0」で置き換えるエラーは報告されません.
  • パッケージ化時にプラットフォームのエラーを報告する可能性があります.これはプラグインを削除する必要があります.upluginファイルの下にホワイトリストコード
  • を追加
    {
    	"FileVersion": 3,
    	"Version": 1,
    	"VersionName": "1.0",
    	"FriendlyName": "MySQLUtility",
    	"Description": "",
    	"Category": "Other",
    	"CreatedBy": "",
    	"CreatedByURL": "",
    	"DocsURL": "",
    	"MarketplaceURL": "",
    	"SupportURL": "",
    	"CanContainContent": true,
    	"IsBetaVersion": false,
    	"Installed": false,
      "Modules": [
        {
          "Name": "MySQLUtility",
          "Type": "Runtime",
          "LoadingPhase": "Default",
          "WhitelistPlatforms": [
            "Win64",
            "Win32",
            "HTML5"
          ]
        }
      ]
    }
    

    テストコードは次の通りです.hファイル
    // Fill out your copyright notice in the Description page of Project Settings.
    
    #pragma once
    
    #include "CoreMinimal.h"
    #include "Kismet/BlueprintFunctionLibrary.h"
    #include "mysql_connection.h"
    #include "mysql_driver.h"
    #include "cppconn/resultset.h"
    #include "cppconn/statement.h"
    #include "MySQLConnectObject.h"
    #include "MyBlueprintFunctionLibrary.generated.h"
    
    using namespace sql;
    /**
     * 
     */
    
    USTRUCT()
    struct FSQLCon
    {
    	GENERATED_USTRUCT_BODY()
    public:
    	
    	Connection* con;
    };
    
    UCLASS()
    class MYSQLUTILITY_API UMyBlueprintFunctionLibrary : public UBlueprintFunctionLibrary
    {
    	GENERATED_BODY()
    
    	UFUNCTION(BlueprintCallable, Category = "MySQL")
    	static UMySQLConnectObject* ConnectMySQL(FString Username,FString Password, FString DataBase);
    	UFUNCTION(BlueprintCallable, Category = "MySQL")
    	static UMySQLConnectObject* exeQueryMySQL(UMySQLConnectObject* con,FString SQL);
    	UFUNCTION(BlueprintCallable, Category = "MySQL")
    	static void CloseMySQL(UMySQLConnectObject* con);
    		
    
    };
    
    

    テストコードは次の通りです.cppファイル
    // Fill out your copyright notice in the Description page of Project Settings.
    
    
    #include "MyBlueprintFunctionLibrary.h"
    #include "Engine/Engine.h"
    
    UMySQLConnectObject* UMyBlueprintFunctionLibrary::ConnectMySQL(FString Username, FString Password,FString DataBase)
    {		
    	Driver *driver;
    	Connection *con=NULL;
    	if (GEngine)
    	{
    
    		try
    		{
    			driver = get_driver_instance();
    			if (Username.IsEmpty() || Password.IsEmpty() || DataBase.IsEmpty())
    			{
    				con = driver->connect("tcp://127.0.0.1:3306", "root", "MySQL125799");
    				con->setSchema("asdf");
    			}
    			else
    			{
    				con = driver->connect("tcp://127.0.0.1:3306", TCHAR_TO_UTF8(*Username), TCHAR_TO_UTF8(*Password));
    				con->setSchema(TCHAR_TO_UTF8(*DataBase));
    			}
    		}
    		catch (SQLException &e)
    		{
    			//cout << "ERROR: SQLException in ";
    			GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR: SQLException in MyBlueprintFunctionLibrary")));
    			GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR:")) + FString(e.what()));
    			if (e.getErrorCode() == 1047) {
    				/*
    				Error: 1047 SQLSTATE: 08S01 (ER_UNKNOWN_COM_ERROR)
    				Message: Unknown command
    				*/
    				GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("
    Your server does not seem to support Prepared Statements at all. "
    ))); } } catch (std::runtime_error &e) { GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR: runtime_error in ")) + TEXT(__FILE__)); GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR:")) + FString(e.what())); } } UMySQLConnectObject* tmp = NewObject<UMySQLConnectObject>(); tmp->con = con; return tmp; } UMySQLConnectObject* UMyBlueprintFunctionLibrary::exeQueryMySQL(UMySQLConnectObject* con, FString SQL) { Statement *stmt = NULL; ResultSet *res = NULL; if (con->con==NULL) { return con; } if (con==NULL||SQL.IsEmpty()) { if (con->con) { stmt = con->con->createStatement(); try { res = stmt->executeQuery("SELECT * from goods"); } catch (SQLException &e) { //cout << "ERROR: SQLException in "; GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR: SQLException in MyBlueprintFunctionLibrary"))); GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR:")) + FString(e.what())); if (e.getErrorCode() == 1047) { /* Error: 1047 SQLSTATE: 08S01 (ER_UNKNOWN_COM_ERROR) Message: Unknown command */ GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("
    Your server does not seem to support Prepared Statements at all. "
    ))); } return con; } catch (std::runtime_error &e) { GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR: runtime_error in ")) + TEXT(__FILE__)); GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR:")) + FString(e.what())); return con; } // sql while (res->next()) { GEngine->AddOnScreenDebugMessage(-1, 15.f, FColor::Red, FString(TEXT("gid ")) + UTF8_TO_TCHAR(res->getString("gid").c_str())); } } delete res; delete stmt; } else { stmt = con->con->createStatement(); try { res = stmt->executeQuery(TCHAR_TO_UTF8(*SQL)); } catch (SQLException &e) { //cout << "ERROR: SQLException in "; GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR: SQLException in MyBlueprintFunctionLibrary"))); GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR:")) + FString(e.what())); if (e.getErrorCode() == 1047) { /* Error: 1047 SQLSTATE: 08S01 (ER_UNKNOWN_COM_ERROR) Message: Unknown command */ GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("
    Your server does not seem to support Prepared Statements at all. "
    ))); } return con; } catch (std::runtime_error &e) { GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR: runtime_error in ")) + TEXT(__FILE__)); GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Red, FString(TEXT("ERROR:")) + FString(e.what())); return con; } // sql while (res->next()) { GEngine->AddOnScreenDebugMessage(-1, 15.f, FColor::Red, FString(TEXT("gid ")) + UTF8_TO_TCHAR(res->getString("gid").c_str())); } delete res; delete stmt; } return con; } void UMyBlueprintFunctionLibrary::CloseMySQL(UMySQLConnectObject* con) { //delete res; //delete stmt; if (con->con) { con->con->close(); } }

    テストコードは次の通りです.cpp
    // Fill out your copyright notice in the Description page of Project Settings.
    
    #pragma once
    
    #include "CoreMinimal.h"
    #include "UObject/NoExportTypes.h"
    #include "mysql_connection.h"
    #include "mysql_driver.h"
    #include "cppconn/resultset.h"
    #include "cppconn/statement.h"
    #include "MySQLConnectObject.generated.h"
    
    /**
     * 
     */
    using namespace sql;
    
    
    UCLASS(BlueprintType)
    class MYSQLUTILITY_API UMySQLConnectObject : public UObject
    {
    	GENERATED_BODY()
    public:
    
    	Connection* con;
    };
    
    

    テストコードは次の通りです.cpp
    // Fill out your copyright notice in the Description page of Project Settings.
    
    
    #include "MySQLConnectObject.h"
    
    
    
    

    パッケージ化時にtry catch文を使用できないことに気づきました.これは幻のデフォルトが無効になっているため、開くには.build.csの下にbEnableExceptions=trueを追加します.その他のbool変数の役割は、ソースコードのModuleRulesクラスのメンバー変数のコメントを表示できます.