Download

[c++] Mysql database error

im trying to make a basic connection with mysql database with this code
mysql_nodes.cpp



bool UMysql_Nodes::SaveData(FString myText)
{
	
        #define host "localhost"
	#define username "username" 
	#define password "password" 
	#define database "db_test"
	MYSQL* conn; conn = mysql_init(NULL);
	if (conn) { 
		mysql_real_connect(conn, host, username, password, database, 0, NULL, 0); 
	} 
	MYSQL_RES* res_set; 
	MYSQL_ROW row; 
	unsigned int i;
	mysql_query(conn, "SELECT char_name FROM characters WHERE id = 1");
	res_set = mysql_store_result(conn);
	unsigned int numrows = mysql_num_rows(res_set);
	if (numrows) {
		row = mysql_fetch_row(res_set);
		if (row != NULL) {
			cout << "Client ID : " << row[0] << endl; cout << "Char Name: " << row[1] << endl; 
		}
	} 
	if (res_set) {
		mysql_free_result(res_set);
	} 
	if (conn) {
		mysql_close(conn); 
	}
	return 0;
}

i get error in mysql_com.h line 322
Error 1 error C2146: syntax error: missing ‘;’ before identifier ‘fd’
mysql_com.h


 my_socket fd;					/* For Perl DBI/dbd */

i attached the full mysql_com.h code as txt file.

Long ago… could be now all wrong. Either comment the offending line and another function definition further down (next error if you comment it) or figure where to include winsock2.h and wsock2_32.lib.

ok, so now i have a lot of same erros in winsock2.h:
Error 26 error C2872 : ’ DWORD ‘: ambiguous symbol
and
Error 27 error C2872 : ’ INT’: ambiguous symbol

Try



#include "AllowWindowsPlatformTypes.h"
#include <winsock2.h>
#include "HideWindowsPlatformTypes.h"


hm… yeah… this solve the ambiguous symbol problem… but…
i receive “error C4101: ‘i’ : unreferenced local variable”
in Mysql_Nodes.cpp line 36


unsigned int i;

if i change to unsigned int i = 0;
i get this…
d5ad89882073b65190324bfac7b6323dbe77ec8c.png

You are linking with the mysql import lib right?

Well if you don’t… link with the mysql import lib. Easiest would be #pragma comment lib thing (comment pragma | Microsoft Docs).

Most important thing to bookmark:

Just googled the right way to include third party libs and found

https://answers.unrealengine.com/questions/76792/link-to-3rd-party-libraries.html

…contains relevant info and links.

:slight_smile:

:confused:
sorry for the question , but is this ? #pragma comment(lib, “libmysql”)

Yea. Maybe with full path in front of the name and .lib at the end. Eventually you should look at the last link and do it all right.

ty for the links.
tryed all thing from the links. linked the mysql libs. but i still get the link error.
maybe is a VS config problem ?

Hi, I have the same error:

1>c:\mysql\include\mysql_com.h(191): error C2146: syntax error : missing ‘;’ before identifier ‘fd’
1>c:\mysql\include\mysql_com.h(191): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\mysql\include\mysql_com.h(366): error C2065: ‘SOCKET’ : undeclared identifier
1>c:\mysql\include\mysql_com.h(366): error C2146: syntax error : missing ‘)’ before identifier ‘s’
1>c:\mysql\include\mysql_com.h(367): error C2059: syntax error : ‘)’

I added this:

#include “AllowWindowPlatformTypes.h”
#include <mysql.h>

And the compilation part worked ok. But then I get an error in the linker:

1>------ Build started: Project: MyProject2, Configuration: Development_Server x64 ------
1> Performing 2 actions (4 in parallel)
1> dal.cpp
1> [2/2] Link MyProject2Server.exe
1> Creating library C:\Users\Luke\Documents\Unreal Projects\MyProject2\Binaries\Win64\MyProject2Server.lib and object C:\Users\Luke\Documents\Unreal Projects\MyProject2\Binaries\Win64\MyProject2Server.exp
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_server_init referenced in function “public: bool __cdecl psMysqlConnection::Initialize(char const *,unsigned int,char const *,char const *,char const *,class LogCSV *)” (?Initialize@psMysqlConnection@@QEAA_NPEBDI000PEAVLogCSV@@@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_server_end referenced in function “public: virtual bool __cdecl psMysqlConnection::Close(void)” (?Close@psMysqlConnection@@UEAA_NXZ)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_thread_init referenced in function “public: bool __cdecl psMysqlConnection::Initialize(char const *,unsigned int,char const *,char const *,char const *,class LogCSV *)” (?Initialize@psMysqlConnection@@QEAA_NPEBDI000PEAVLogCSV@@@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_num_rows referenced in function “public: __cdecl psResultSet::psResultSet(struct st_mysql *)” (??0psResultSet@@QEAA@PEAUst_mysql@@@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_num_fields referenced in function “public: __cdecl psResultSet::psResultSet(struct st_mysql *)” (??0psResultSet@@QEAA@PEAUst_mysql@@@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_affected_rows referenced in function “public: unsigned long __cdecl psMysqlConnection::Command(char const *,…)” (?Command@psMysqlConnection@@QEAAKPEBDZZ)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_insert_id referenced in function “public: unsigned __int64 __cdecl psMysqlConnection::GenericInsertWithID(char const *,char const * *,class TArray<class FString,class FDefaultAllocator> &)” (?GenericInsertWithID@psMysqlConnection@@QEAA_KPEBDPEAPEBDAEAV?$TArray@VFString@@VFDefaultAllocator@@@@@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_error referenced in function “public: char const * __cdecl psMysqlConnection::GetLastError(void)” (?GetLastError@psMysqlConnection@@QEAAPEBDXZ)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_init referenced in function “public: bool __cdecl psMysqlConnection::Initialize(char const *,unsigned int,char const *,char const *,char const *,class LogCSV *)” (?Initialize@psMysqlConnection@@QEAA_NPEBDI000PEAVLogCSV@@@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_real_connect referenced in function “public: bool __cdecl psMysqlConnection::Initialize(char const *,unsigned int,char const *,char const *,char const *,class LogCSV *)” (?Initialize@psMysqlConnection@@QEAA_NPEBDI000PEAVLogCSV@@@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_query referenced in function “public: unsigned long __cdecl psMysqlConnection::Command(char const *,…)” (?Command@psMysqlConnection@@QEAAKPEBDZZ)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_store_result referenced in function “public: __cdecl psResultSet::psResultSet(struct st_mysql *)” (??0psResultSet@@QEAA@PEAUst_mysql@@@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_options referenced in function “public: bool __cdecl psMysqlConnection::Initialize(char const *,unsigned int,char const *,char const *,char const *,class LogCSV *)” (?Initialize@psMysqlConnection@@QEAA_NPEBDI000PEAVLogCSV@@@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_free_result referenced in function “public: virtual __cdecl psResultSet::~psResultSet(void)” (??1psResultSet@@UEAA@XZ)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_data_seek referenced in function “public: virtual int __cdecl psResultRow::Fetch(int)” (?Fetch@psResultRow@@UEAAHH@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_field_seek referenced in function “public: virtual char const * __cdecl psResultRow::operator](char const *)” (??ApsResultRow@@UEAAPEBDPEBD@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_fetch_row referenced in function “public: virtual int __cdecl psResultRow::Fetch(int)” (?Fetch@psResultRow@@UEAAHH@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_fetch_field referenced in function “public: virtual char const * __cdecl psResultRow::operator](char const *)” (??ApsResultRow@@UEAAPEBDPEBD@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_escape_string referenced in function “public: void __cdecl psMysqlConnection::Escape(class FString &,char const *)” (?Escape@psMysqlConnection@@QEAAXAEAVFString@@PEBD@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_stmt_init referenced in function “public: __cdecl dbRecord::dbRecord(struct st_mysql *,char const *,char const *,unsigned int,class LogCSV *,char const *,unsigned int)” (??0dbRecord@@QEAA@PEAUst_mysql@@PEBD1IPEAVLogCSV@@1I@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_stmt_prepare referenced in function “public: virtual bool __cdecl dbInsert::Prepare(void)” (?Prepare@dbInsert@@UEAA_NXZ)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_stmt_execute referenced in function “public: virtual bool __cdecl dbRecord::Execute(unsigned int)” (?Execute@dbRecord@@UEAA_NI@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_stmt_param_count referenced in function “public: virtual bool __cdecl dbRecord::Execute(unsigned int)” (?Execute@dbRecord@@UEAA_NI@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_stmt_bind_param referenced in function “public: virtual bool __cdecl dbRecord::Execute(unsigned int)” (?Execute@dbRecord@@UEAA_NI@Z)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_stmt_close referenced in function “public: virtual __cdecl dbRecord::~dbRecord(void)” (??1dbRecord@@UEAA@XZ)
1>dal.cpp.obj : error LNK2019: unresolved external symbol mysql_close referenced in function “public: virtual __cdecl psMysqlConnection::~psMysqlConnection(void)” (??1psMysqlConnection@@UEAA@XZ)
1>C:\Users\Luke\Documents\Unreal Projects\MyProject2\Binaries\Win64\MyProject2Server.exe : fatal error LNK1120: 26 unresolved externals
1> -------- End Detailed Actions Stats -----------------------------------------------------------

I tried to add the lib to the VC project settings and also in Source\MyProject2\MyProject2.Build.cs in the form of:

PublicAdditionalLibraries.Add(“C:\mysql\lib\opt\libmysql.lib”);

But I still get the same error. Any ideas?

I hope you’ve done your homework on this one… linking mysql connectors or the client lib in UE4 is a nightmare. Linking the mysql connectors to anything using current development tools can be a serious challenge. Depending on how you’re linking, you may need to build the connector (or client lib) from source with the same tools you’re using to compile with UE4. If dynamic linking, you need to make sure that you are also linking against the static import lib and the binaries need to be copied to the executable directory of your project as well. It’s gonna get frustrating to get this working, you’ve been warned… lol

Keep in mind that you don’t need to use a MySQL connector/lib to connect to MySQL via c++. You could consider using ADO to do it with a hell of a lot less headaches.

Hi, I have knowledge about the difference between static and dynamic linking, but do I know if I’m compiling dynamic or static in Unreal Engine? I’m using the default configuration and using Auto - Development Server - Win64 in the options at the top.

I tried to search the mysql_server_init with an utility to inspect the .lib files (dumpbin.exe) to see if that function was contained in the lib. Actually this is what I see:

Version : 0
Machine : 14C (x86)
TimeDateStamp: 46F81D8F Mon Sep 24 22:26:55 2007
SizeOfData : 00000023
DLL name : LIBMYSQL.dll
Symbol name : _mysql_server_init@12
Type : code
Name type : undecorate
Hint : 98
Name : mysql_server_init

This means it’s contained into it. Being 2007 can be a bit old, but I have another project (not made with Unreal) and that lib works ok. In that case I use VS 2010 to compile.

I decided to compile win32 configuration and not win64 and IT WORKED!! So you have to ensure the libmysql.lib you use is the right version. :smiley: :smiley: :smiley: :smiley:

Please note that the linker error was searching for “mysql_server_init” in win64, while it was searching for “_mysql_server_init@12” in win32, which is the string present in the dump above.

i tryed to use 64 mysql libs , but the mysql downloads are corrupted t-t. i tryed to compile in win32 and i get more errors.
#EDIT

I downloaded mysql connector x64, and linked the libs from connector.
now it worked. i compiled; but when i open my project , now he says ’ missing modules '.

K I’ll try to provide some info to get this working for you. Now when you say you are working with MySQL Connector, are you using the C connector (6.1) or the C++ connector. If it’s the C++ connector the process should be similar but you may have some clashes between types defined in the C++ connector and UE4.

Also from what I’ve gathered from the code posted you are trying to link dynamically correct? If so then this will be of use to you.

This example will use the MySQL C Connector 6.1 and will be linking dynamically via the DLL and the static import lib (libmysql.dll and libmysql.lib). I should also mention that I compiled the connector myself to avoid any incompatibility problems due to the ancient development tools used to build the binaries distributed by MySQL, although I don’t think this is a problem when dynamic linking (only is static linking is it a problem I think).

Personally, I’ve been linking with the x64 version since my build is targetting windows x64 only but the same will work for x86 as well.

Also note, I’ve implemented this into a module for modularity.

At the root of your project hierarchy, create a folder named ThirdParty. i.e.:

MyProject
[INDENT]Binaries
Build
Config
Content
Intermediate
Saved
Source
ThirdParty
MyProject.sln
MyProject.uproject
[/INDENT]

Within the ThirdParty folder, add the MySQL Connector.C 6.1 folder. You can exclude the bin and docs folder from the connector but the structure within the ThirdParty folder should look like this:

ThirdParty
[INDENT]MySQL Connector.C 6.1
[INDENT]include
lib[/INDENT][/INDENT]

The include folder will have the required header files. The bin folder will have the required libmysql.dll and libmysql.lib.

I’m going to name the module this will be used in MySQLSupport for this example.

In my projects source directory I’ll create the folder structure for the module as follows:

Source
[INDENT]MyProject (my games source directory)
MySQLSupport (my modules source directory)
[INDENT]Public
[INDENT]MySQLSupport.h
Private
MySQLSupport.cpp
MySQLSupportPrivatePCH.h[/INDENT]
MySQLSupport.Build.cs[/INDENT][/INDENT]

I’m sure you already know the process of creating a module and how the source for it should be structured but I’m showing it here for anyone else that comes across this thread seeking help, and the structure matters later on when we are locating the relative path to the ThirdParty folder in the module’s build file.

For the sake of providing complete example, here is an example header file for the module implementation (MySQLSupport.h):


#pragma once

#include "ModuleManager.h"

class IMySQLSupport : public IModuleInterface
{
public:

	static inline IMySQLSupport& Get()
	{
		return FModuleManager::LoadModuleChecked<IMySQLSupport>("MySQLSupport");
	}

	static inline bool IsAvailable()
	{
		return FModuleManager::Get().IsModuleLoaded("MySQLSupport");
	}
};

and here is the source file for that header (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()
{

}


and of course, here is the private precompiled header for the module (MySQLSupportPrivatePCH.h):


#pragma once

#include "Engine.h"


Short and sweet lol

Now for the build file (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
    }
}

As you can see, I built up my path strings rather explicitly but it’s for clarity so each path’s use is very clear. So this will handle things on the UBT side but we still need to tell visual studio where to find these files too.

With your project open in Visual Studio, right click on the Project, select Properties and navigate to: Configuration Properties → VC++ Directories and add the following settings:

Include Directories: (add the path to the include folder in MySQL Connector.C 6.1)
Library Directories: (add the path to the lib folder in MySQL Connector.C 6.1)

Now let’s add a class that actually connects to MySQL so we can make sure everything works.

I’ll call this class MySQLTest. It will be a standard c++ class (not derived from UObject) just for simplicity of this example and I am going to add it to my module’s Private directory.

Here is the header file (MySQLTest.h):


#pragma once

#include "AllowWindowsPlatformTypes.h"
#include <winsock2.h>
#include <mysql.h>
#include "HideWindowsPlatformTypes.h"

class MySQLTest
{
public:
	MySQLTest();
	~MySQLTest();

	int32 GetMySQLVersion() const;
private:
	MYSQL* conn;
	int32 version = -1;
};

Notice how the <winsock2.h> and <mysql.h> are wrapped in the #includes to allow windows platform types. This is important. The compiler will yell at you (and it might even attack you!) if you don’t do this.

and here is the source file (MySQLTest.cpp):


#include "MySQLSupportPrivatePCH.h"
#include "MySQLTest.h"

#pragma comment(lib, "libmysql.lib")



MySQLTest::MySQLTest()
{
	conn = mysql_init(NULL);
	mysql_real_connect(conn, "localhost", "user1", "supersecretpassword", "somedatabase", 3308, NULL, 0);
	version = mysql_get_server_version(conn);
	mysql_close(conn);
}

MySQLTest::~MySQLTest()
{
	conn = NULL;
}

int32 MySQLTest::GetMySQLVersion() const
{
	return version;
}

Nothing too fancy here. This code just simply connects to the specified server (localhost in this case) using the specified user (user1) and password (supersecretpassword) specifying a database instance and a port and queries the database for it’s version number. I specified a default initial value of version as -1 so I can easily identify if there is no setting of the value. The really sexy part here is the variable MYSQL conn*. This is a pointer to our MySQL connection that will be created. I’m not going to get into a MySQL lesson here. This is just a super quick and simple test to make sure everything is working and that we can connect to our database.

Just make sure that the parameters passed to the connect function are valid for your use. For example, I don’t use port 3308.

Other things to note is the #pragma comment(lib, “libmysql.lib”). This handles defining the static import lib in-place.

The last thing you need to do before compiling this is to copy libmysql.lib and libmysql.dll into your project’s bin directory of the target platform (i.e. Binaries/Win64 or Binaries/Win32). This is a gotcha of Unreal Engine 4 at the moment but fingers crossed that this will get fixed in the future.

Oh, and one last thing. Just a minor detail but an important one. Make sure that your project’s target file(s) are specifying the module as an output binary and be sure to add your module to your project’s uproject file.

Now go ahead and compile the code. If you followed along right, you should see everything build nicely.

If you would like to test this out in the editor, just create something that you can spawn in the gameworld that will hold an instance of this class within it and wraps a call to the GetMySQLVersion() function.

One other thing to keep in mind is that if for some reason you happen to regenerate your visual studio project files, the Include Directories and Include Libraries paths you had set in visual studio will have been wiped and need to be set again manually.

Good luck and I hope this clears up problems of anyone trying like hell to get MySQL access within UE4. Oh, and I’ll leave wrapping the MySQL API to you… heh

9KGameStudio
Thanks for the help man , i make some changes for use this in blueprint nodes, and its works fine :smiley:
Also thanks to Mikand79 and Talad


Now i will try to finish this with ‘SELECT’,‘UPDATE’ and etc . . . XD
This is the best tutorial for connection with mysql in C ++ .FOR UE4.
Very Easy to understand
:smiley:

Hi,How I can use in bluePrint? Please Help me,I can work in c++.Thanks very much!