2023年11月29日发(作者:)
UE4学习笔记--连接MySQL数据库(C++)
UE4学习笔记--连接MySQL数据库
我个⼈是个⽐较⽔的⼈,在学校没好好学程序,不误正业的玩建模,现在美术和程序都不⾏……想想还是重新认真学程序
吧,先从记笔记开始,话说我还是第⼀次写博客……
我是跟着⼏位⼤佬的博客做的,记录⼀下⾃⼰的问题,以免以后忘记.
⼤佬的链接如下:
.
.
UE4连接MySQL数据库步骤
1. ⾸先搞到MySQL的连接⽂件 MySQL Connector.C 6.1(在C:Program Files MySQL⽂件下,注意要看好⾃⼰的程序需要的是32
位的库还是64位的库)
2. 然后到项⽬⽂件夹下新建⽂件夹ThirdParty,并将连接⽂件复制到ThirdParty⽂件夹下,将连接⽂件的⽂件名中的空格全部删去
3. 将lib⽂件夹下的dll⽂件放到项⽬⽂件夹下的Binaries⽂件夹
4. 常规的C++添加第三⽅库的⽅法对虚幻不是很适⽤,可能会出现⼀系列问题,所以要在插件模块的.下添加以下代码
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; //.
获取本⽂件的路径
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/");//
获取第三⽅库的连接⽂件的路径
。
string MySQLConnectorDLLName = Path.Combine(MySQLConnectorLibraryPath, "");//
获取第三⽅动态链接库⽂件的路径。
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);//
注册第三⽅库的连接⽂件。
//(MySQLConnectorDLLName);
bEnableUndefinedIdentifierWarnings = false;
}
}
6. 在⼯程所对应的.的⽂件中加上bEnableUndefinedIdentifierWarnings = false;就不会报没有将“某某某”定义为预处理器
宏,⽤“0”替换“#if/#elif”的错误了
7. 在打包时可能会报平台的错误,这需要去插件的.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"
]
}
]
}
测试代码如下 MyBlueprintFunctionLibrary.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 "ted.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);
};
测试代码如下 ⽂件
// 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("nYour 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("nYour 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("nYour 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();
con->con->close();
}
}
测试代码如下
// 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 "ted.h"
/**
*
*/
using namespace sql;
UCLASS(BlueprintType)
class MYSQLUTILITY_API UMySQLConnectObject : public UObject
{
GENERATED_BODY()
public:


发布评论