mariaDB설치
내 컴퓨터 ip주소 확인하려면 cmd에 ipconfig입력
mariaDB 백그라운드 실행되는 동안 많은 메모리 차지
window + R => control 검색 -> 컴퓨터 관리 -> 서비스 및 응용프로그램 -> 서비스 -> mariaDB찾고 수동으로 바꾼다.
이렇게 하면 프로세스는 안잡아먹지만, mariaDB사용불가. 사용할 땐 다시 켜줘야 함
Windows 11에서 컴퓨터 관리를 여는 방법 - TABMODE
컴퓨터 관리는, 로컬 컴퓨터와 원격 컴퓨터를 관리할 수 있는 Windows 관리 도구 모음입니다. 컴퓨터 관리 작업에 필요한 도구에 쉽게 액세스할 수 있습니다. Windows 11에서 컴퓨터 관리를 여는 방법
www.tabmode.com
stock 테이블 생성
CREATE TABLE stock
( id INT(11) not null auto_increment,
name VARCHAR(100) not null,
description TEXT null,
listed DATETIME not null,
founder VARCHAR(30) null,
bought INT(11) null,
PRIMARY KEY(id) );
간단히 설명하면
id : int형 최대 11자리, 데이터 추가할때마다 자동으로 1씩 증가
name : variable character (char형) 최대 100, null일 수 없음
description: 많은 양의 텍스트를 담을 수 있는 TEXT형 null가능
PRIMARY KEY(id) : 기본키를 id로 설정한다는 것으로, 보통 기본키는 유일한 것으로 정해주는 것으로 알고 있음

INSERT : (CRUD의 C)
INSERT INTO stock (name, listed, founder, bought)
VALUES ('이용환', '2023-05-31 12:00:00', '삼성전자', 100);
만약 모든 속성들을 다 입력한다면 ()괄호는 필요없다. 하지만 그게 아닐 경우 () 필요\
확인하려면 SELECT *FROM stock;

잘못해서 두번 들어갔지만 데이터 잘 들어감

테이블의 속성을 하나라도 추가하면 일일히 모든 데이터의 추가한 속성을 다시 관리해야 하기 때문에
순서 잘 맞춰서 넣을것. 나중에 관리하기 쉽다(잘 이해 못함)
SELECT : CRUD의 R. (데이터 읽기)
select와 from은 항상 따라다님. from은 select를 어디에서 할지 알려주는 것이기 때문에
SELECT id, SELECT NAME, SELECT founder.. 할 거 없이
SELECT id, NAME, founder 처럼 쉼표로 구분 가능 (int a,b,c; 처럼)

필드를 모두 가져오고 싶다면, SELECT *FROM stock 하면 됨 여기서도 *은 모두의 의미
WHERE절 : 조건을 부여하여 특정 값에 접근할 수 있다.
논리연산자 사용가능, BETWEEN, LIKE, IN
ex) LIKE a : a 로 시작하는 모든것
ex) LIKE %a : a 로 끝나는 모든
ex) IN ~ : 집합에 소속하는 모든 (?)
AND, OR 등으로 여러개 의 조건 판별 가능
WHERE NOT bought > 150 AND NAME = '김지훈'; 등 NOT을 사용해 이 조건만 제외시킬 수 있음

UPDATE문
- 테이블에 존재하는 값을 변경
- 특정 컬럼에 해당하는 값을 변경
UPDATE stock
SET bought = 1500, description = "'WDC 발표 이후 주가하락'
WHERE NAME = '이용환' AND founder = '애플';
DELETE
사용 지양
DELETE와 같이 쓰는 WHERE문도 조심해서 사용
1.테이블 생성
2. (Playfab사용한) 로그인 씬을 ' 다른 이름으로 저장 '

CREATE TABLE IF NOT EXISTS player (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(64) DEFAULT NULL,
password varchar(64) DEFAULT NULL,
nickname varchar(64) DEFAULT NULL,
email varchar(128) DEFAULT NULL,
confirmationcode varchar(128) DEFAULT NULL,
confirmationdate datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS login_history (
id int(11) NOT NULL AUTO_INCREMENT,
player_id int(11) NOT NULL,
login_time datetime NOT NULL,
logout_time datetime DEFAULT NULL,
login_data varchar(1024) DEFAULT NULL,
PRIMARY KEY (id),
KEY player_id (player_id),
CONSTRAINT login_history_fk_1 FOREIGN KEY (player_id) REFERENCES player (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
여기서 보면 Loginhistory테이블의 player_id는 FK인데, 이는 독립적으로 데이터를 생성할 수 없고 player테이블의 id가 먼저 존재해야 데이터를 추가할 수 있다는 뜻이다

유니티에서 c#으로 얘가 먼저 php를 만든다. 그런 다음 php를 아파치에 넘겨주고, 아파치에서 mariadb로 넘겨준다.
그리고 파싱을 해서 유니티에 다시 뿌려준다.
유니티에서 playfab과 sql연동자료를 찾아보면 거의 다 php를 사용한 이런 방식을 사용한다.
아파치는 설치만 하면 되지만, php를 사용한다는 것은 배워야 한다는 것. 넘겨줄때 php양식에 맞춰서 한다던지의(form(?) 태그 사용) 내용을 알아야 한다.
그래서 이런 방식이 아니라

ODBC방식활용
c#에서 ADO를 이용한 Database연동방식을 사용 dll을 받아 활용한다

위 과정에 대한 설명 추가 필요
데이터를 보내면 DataAdaptor와 커넥션(설치한 dll)을 거쳐 마리아 디비에 접근, 같은 방식으로 되돌아가면서
로컬 Dataset에 전송(?)

자원을 사용할 때 항상 open -> 사용 -> close를 해야 함. 객체지향에서도 객체를 생성했다 하고 다 사용했다 하면 이렇게 릴리즈해줘야함.
대신 c#에서는 가비지콜렉터가 알아서 해주기 때문에 직접 구현은 하지 않지만, 원래 해줘야 함 .
https://dev.mysql.com/downloads/
MySQL :: MySQL Community Downloads
The world's most popular open source database Contact MySQL | Login | Register
dev.mysql.com

위 사이트에서 dll을 받을 수 있는데, 8.~버전(?)이 유니티 2020 2022 버전에서 오류가 난다고 한다.
유니티에서 이 커넥터 최신버전을 사용할 수 있게끔 업데이트가 안된다고 한다 (개발자 포럼)
https://timeboxstory.tistory.com/139 이 블로그에는 Connecter/NET을 다운로드하라한다 실제로 ODBC로 다운받아보니 Mysql.Data.dll파일 존재 x
https://downloads.mysql.com/archives/c-net/
나중에 웹사이트에서 커넥터 찾아서 dll다운받고자 할 때 버전에 대해 잘 알아보고 설치할 것.
지금은 커넥터 구버전 dll을 받아서 사용
PlayFab로그인, 회원가입 기능을 마리아 DB에 연결해보자

(추가해야될거) : 플레이팹 ID를 게임매니저의 필드로 선언해 넣고, DontDestroyonLoad적용해서 씬이 이동해도 유지되도록 해줘야 함
그리고 MariaDB에서 받은 유저 ID(res)를
<LoginMariaDB()>에서
GameObject.Find("GameManager").GetComponent<GameManager>().myGlobalPlayFabId = res.ToString(); 해주는것
이전에 구성했더 화면으로 로그인, 회원가입 모두 정상적으로 되고 유저 정보는 PlayFab에 정상적으로 표시된다.
아래에 PlayFab 구현문서와 위 화면까지 구현된 파일을 올려놨으니 다운로드 받으면 된다
https://github.com/zhun0922/PlayFabInit
GitHub - zhun0922/PlayFabInit: 플레이팹 초기_로그인,회원가입 베이스기능
플레이팹 초기_로그인,회원가입 베이스기능. Contribute to zhun0922/PlayFabInit development by creating an account on GitHub.
github.com

먼저 위의 dll파일을 Assets/Plugins 디렉토리 생성해서 넣어주고 PlayFab씬을 복사한다.
-> 오류발생
https://ckbcorp.tistory.com/1284
C# 에서 MariaDB 연결할 때, MySqlConnection.Open() System.InvalidCastException: Object cannot be cast from DBNull to other
오프라인에서 VS C# + MariaDB 를 돌려야 할 일이 있어서 이래저래 설치하고 Visual Studio , Maria DB, heidisql portable ( 윈도우용 MariaDB Client), Mysql Connector 6.5 를 설치하고 돌려봤는데, 빌드는 되는데 자꾸 DB
ckbcorp.tistory.com
결론 : MariaDB 10.9이하 쓰던가 mysqlConnector사용
10.6으로 받고
https://timeboxstory.tistory.com/139
[Unity] 유니티에서 Mysql, MariaDB 연동하고 조회하기
✔ Unity - Mysql, 마리아 DB 연동하기 mysql dll import , mysql select, update, insert MS-SQL은 유니티에 내장되어있어서 쓰기가 편한데 .. Mysql, Maria DB는 별도 DLL을 구해서 사용해야되니까 불편하당 ㅠ_ㅠ 유니티
timeboxstory.tistory.com
RegisterDB -> player테이블에 Insert -> LoginDB -> 데이터 가져오고, ID가져와서 GameManger필드에 넣어줌
-> 동시에 LoginToMariaDBLoginHistory()에서 LoginHistory테이블에 Insert로 데이터 넣는다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using MySql.Data.MySqlClient;
using MySql.Data;
using System;
using System.Data;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
public class LoginSignupMariaDBManager : MonoBehaviour
{
//private MySqlConnection connection;
private MySqlConnection myConnection = null;
private MySqlCommand myCommand = null;
private MySqlDataReader myDataReader = null;
public TMP_InputField inputUserID;
public TMP_InputField inputPassword;
public TMP_InputField inputEmail;
public TMP_Text displayMessage;
private string username;
private string password;
private string email;
//---------------------------------------------------
// Start is called before the first frame update
void Start()
{
SetupSQLConnection();
}
// Update is called once per frame
void Update()
{
}
//--------------------------
public void UsernameValueChanged()
{
username = inputUserID.text.ToString();
}
public void PasswordValueChanged()
{
password = inputPassword.text.ToString();
}
public void EmailValueChanged()
{
email = inputEmail.text.ToString();
}
//-------------------------- SQLConnect
private void SetupSQLConnection()
{
if (myConnection == null)
{
string connectionString =
"SERVER=61.245.246.242; Port=3308; " +
"DATABASE=metaverse; " +
"UID=wonkwangdc; " +
"PASSWORD=wkdc2017;";
try
{
myConnection = new MySqlConnection(connectionString);
//connection.Open();
Debug.Log("[MariaDB Connection] Connected successfully ..");
displayMessage.text = "[MariaDB Connection] Connected successfully ..";
}
catch (MySqlException ex)
{
Debug.LogError("[MariaDB Connection Error] " + ex.ToString());
displayMessage.text = "[MariaDB Connection Error] " + ex.ToString();
}
}
}
private bool CheckDataForMariaDB(int p)
{
if (p == 1) // Signup 일 때
{
Debug.Log("Signup [" + username + " " + password + " " + email + "]");
if ((username != null) && (password != null) && (email != null))
{
return true;
}
else
{
Debug.Log("[INPUT ERROR] User input has an ERROR (NOT Enough to signup)");
displayMessage.text = "[INPUT ERROR] User input has an ERROR (NOT Enough to signup)";
return false;
}
}
else if (p == 2) // Login 일 때
{
Debug.Log("Login [" + username + " " + password + "]");
if ((username != null) && (password != null))
{
return true;
}
else
{
Debug.Log("[INPUT ERROR] User login input has an ERROR (NOT Enough to login)");
displayMessage.text = "[INPUT ERROR] User login input has an ERROR (NOT Enough to login)";
return false;
}
}
else
{
return false;
}
}
// --------------------------------- SINGUP
public void RegisterMariaDB()
{
if (CheckDataForMariaDB(1))
{
Debug.Log("Signup is continued ..");
//RegisterUserToMariaDBPlayer();
if (RegisterUserToMariaDBPlayer())
{
inputUserID.text = "";
inputPassword.text = "";
inputEmail.text = "";
displayMessage.text = "Ok, 정상적으로 회원가입되었습니다.";
Debug.Log("Ok, 정상적으로 회원가입되었습니다.");
}
}
else
{
displayMessage.text = "[ERROR] Error is occurred during your register ..";
Debug.LogError("[ERROR] Error is occurred during your register ..");
}
}
private bool RegisterUserToMariaDBPlayer()
{
string currentDateTimeValue = "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
string usernameValue = "'" + username + "'";
string passwordValue = "'" + password + "'";
string emailValue = "'" + email + "'";
//string commandText = string.Format("INSERT INTO daily_log (username, user_id) VALUES ({0}, {1})", "'megaplayer'", 10);
string commandText = string.Format(
"INSERT INTO player " +
"(username, password, email, confirmationdate) " +
"VALUES ({0}, {1}, {2}, {3})",
usernameValue, passwordValue, emailValue, currentDateTimeValue
);
Debug.Log(commandText);
if (myConnection != null)
{
//MySqlCommand command = connection.CreateCommand();
//command.CommandText = commandText;
myCommand = myConnection.CreateCommand();
myCommand.CommandText = commandText;
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
return true;
}
catch (System.Exception ex)
{
displayMessage.text = "[MariaDB SQL Error] " + ex.ToString();
Debug.LogError("[MariaDB SQL Error] " + ex.ToString());
return false;
}
}
else
{
displayMessage.text = "[MariaDB Error] Connection error ..";
Debug.LogError("[MariaDB Error] Connection error ..");
return false;
}
}
//----------------------------- LOGIN
public void LoginMariaDB()
{
if (CheckDataForMariaDB(2))
{
Debug.Log("Login is continued ..");
int res = LoginToMariaDBPlayer(); //playerID반환 유저가 아무도 없다면 -1 반환
if (res > 0)
{
GameObject.Find("GameManager").GetComponent<GameManager>().myGlobalPlayFabId = res.ToString();
LoginToMariaDBLoginHistory(res);
}
else
{
displayMessage.text = "[" + res + "] Login failed ...";
Debug.Log("[" + res + "] Login failed ...");
inputUserID.text = "";
inputPassword.text = "";
}
}
else
{
displayMessage.text = "[ERROR] Error is occurred during your login ..";
Debug.LogError("[ERROR] Error is occurred during your login ..");
}
}
//private DataTable LoginToMariaDBPlayer()
private int LoginToMariaDBPlayer()
{
//DataTable dt = new DataTable();
string commandTextSelect = string.Format(
"SELECT * FROM player WHERE username='" + username + "' AND password='" + password + "'"
);
Debug.Log(commandTextSelect);
myConnection.Open(); //데이터 오픈
//MySqlDataAdapter adapter = new MySqlDataAdapter(commandTextSelect, myConnection); //어댑터 만든 다음
//adapter.Fill(dt); //Fill시켜야 하는데, 요즘 리더에서 이 기능을 다 해주는 느낌이라 주석처리
myCommand = new MySqlCommand(commandTextSelect, myConnection);
myDataReader = myCommand.ExecuteReader();
int playerID = -1; //데이터가 없는것
while (myDataReader.Read()) //데이터가 여러개있기 때문에 반복해서 접근
{
Debug.Log(myDataReader[0] + "-" + myDataReader[1] + "-" + myDataReader[3] + "-" + myDataReader[6]);
playerID = (int)myDataReader[0]; //ID(key)는 하나씩 증가, 14번째 회원가입 한 유저는 ID 14.
}
myConnection.Close();
//return dt;
return playerID;
}
private void LoginToMariaDBLoginHistory(int id)
{
//다른 테이블인 LoginHistory테이블에 데이터 넣어주는것
string currentDateTimeValue = "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
string usernameValue = "'" + username + "'";
string commandText = string.Format(
"INSERT INTO login_history (player_id, login_time) " +
"VALUES ({0}, {1})",
id, currentDateTimeValue
);
Debug.Log(commandText);
if (myConnection != null)
{
myCommand = myConnection.CreateCommand();
myCommand.CommandText = commandText;
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
StartGame();
}
catch (System.Exception ex)
{
displayMessage.text = "[MariaDB SQL Error] " + ex.ToString();
Debug.LogError("[MariaDB SQL Error] " + ex.ToString());
}
}
else
{
displayMessage.text = "[MariaDB Error] Connection error ..";
Debug.LogError("[MariaDB Error] Connection error ..");
}
}
//------------------- Game Start !
void StartGame()
{
displayMessage.text = "Now, start the game, enjoy it";
Debug.Log("Now, start the game, enjoy it");
}
}
mariaDB설치
내 컴퓨터 ip주소 확인하려면 cmd에 ipconfig입력
mariaDB 백그라운드 실행되는 동안 많은 메모리 차지
window + R => control 검색 -> 컴퓨터 관리 -> 서비스 및 응용프로그램 -> 서비스 -> mariaDB찾고 수동으로 바꾼다.
이렇게 하면 프로세스는 안잡아먹지만, mariaDB사용불가. 사용할 땐 다시 켜줘야 함
Windows 11에서 컴퓨터 관리를 여는 방법 - TABMODE
컴퓨터 관리는, 로컬 컴퓨터와 원격 컴퓨터를 관리할 수 있는 Windows 관리 도구 모음입니다. 컴퓨터 관리 작업에 필요한 도구에 쉽게 액세스할 수 있습니다. Windows 11에서 컴퓨터 관리를 여는 방법
www.tabmode.com
stock 테이블 생성
CREATE TABLE stock
( id INT(11) not null auto_increment,
name VARCHAR(100) not null,
description TEXT null,
listed DATETIME not null,
founder VARCHAR(30) null,
bought INT(11) null,
PRIMARY KEY(id) );
간단히 설명하면
id : int형 최대 11자리, 데이터 추가할때마다 자동으로 1씩 증가
name : variable character (char형) 최대 100, null일 수 없음
description: 많은 양의 텍스트를 담을 수 있는 TEXT형 null가능
PRIMARY KEY(id) : 기본키를 id로 설정한다는 것으로, 보통 기본키는 유일한 것으로 정해주는 것으로 알고 있음

INSERT : (CRUD의 C)
INSERT INTO stock (name, listed, founder, bought)
VALUES ('이용환', '2023-05-31 12:00:00', '삼성전자', 100);
만약 모든 속성들을 다 입력한다면 ()괄호는 필요없다. 하지만 그게 아닐 경우 () 필요\
확인하려면 SELECT *FROM stock;

잘못해서 두번 들어갔지만 데이터 잘 들어감

테이블의 속성을 하나라도 추가하면 일일히 모든 데이터의 추가한 속성을 다시 관리해야 하기 때문에
순서 잘 맞춰서 넣을것. 나중에 관리하기 쉽다(잘 이해 못함)
SELECT : CRUD의 R. (데이터 읽기)
select와 from은 항상 따라다님. from은 select를 어디에서 할지 알려주는 것이기 때문에
SELECT id, SELECT NAME, SELECT founder.. 할 거 없이
SELECT id, NAME, founder 처럼 쉼표로 구분 가능 (int a,b,c; 처럼)

필드를 모두 가져오고 싶다면, SELECT *FROM stock 하면 됨 여기서도 *은 모두의 의미
WHERE절 : 조건을 부여하여 특정 값에 접근할 수 있다.
논리연산자 사용가능, BETWEEN, LIKE, IN
ex) LIKE a : a 로 시작하는 모든것
ex) LIKE %a : a 로 끝나는 모든
ex) IN ~ : 집합에 소속하는 모든 (?)
AND, OR 등으로 여러개 의 조건 판별 가능
WHERE NOT bought > 150 AND NAME = '김지훈'; 등 NOT을 사용해 이 조건만 제외시킬 수 있음

UPDATE문
- 테이블에 존재하는 값을 변경
- 특정 컬럼에 해당하는 값을 변경
UPDATE stock
SET bought = 1500, description = "'WDC 발표 이후 주가하락'
WHERE NAME = '이용환' AND founder = '애플';
DELETE
사용 지양
DELETE와 같이 쓰는 WHERE문도 조심해서 사용
1.테이블 생성
2. (Playfab사용한) 로그인 씬을 ' 다른 이름으로 저장 '

CREATE TABLE IF NOT EXISTS player (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(64) DEFAULT NULL,
password varchar(64) DEFAULT NULL,
nickname varchar(64) DEFAULT NULL,
email varchar(128) DEFAULT NULL,
confirmationcode varchar(128) DEFAULT NULL,
confirmationdate datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS login_history (
id int(11) NOT NULL AUTO_INCREMENT,
player_id int(11) NOT NULL,
login_time datetime NOT NULL,
logout_time datetime DEFAULT NULL,
login_data varchar(1024) DEFAULT NULL,
PRIMARY KEY (id),
KEY player_id (player_id),
CONSTRAINT login_history_fk_1 FOREIGN KEY (player_id) REFERENCES player (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
여기서 보면 Loginhistory테이블의 player_id는 FK인데, 이는 독립적으로 데이터를 생성할 수 없고 player테이블의 id가 먼저 존재해야 데이터를 추가할 수 있다는 뜻이다

유니티에서 c#으로 얘가 먼저 php를 만든다. 그런 다음 php를 아파치에 넘겨주고, 아파치에서 mariadb로 넘겨준다.
그리고 파싱을 해서 유니티에 다시 뿌려준다.
유니티에서 playfab과 sql연동자료를 찾아보면 거의 다 php를 사용한 이런 방식을 사용한다.
아파치는 설치만 하면 되지만, php를 사용한다는 것은 배워야 한다는 것. 넘겨줄때 php양식에 맞춰서 한다던지의(form(?) 태그 사용) 내용을 알아야 한다.
그래서 이런 방식이 아니라

ODBC방식활용
c#에서 ADO를 이용한 Database연동방식을 사용 dll을 받아 활용한다

위 과정에 대한 설명 추가 필요
데이터를 보내면 DataAdaptor와 커넥션(설치한 dll)을 거쳐 마리아 디비에 접근, 같은 방식으로 되돌아가면서
로컬 Dataset에 전송(?)

자원을 사용할 때 항상 open -> 사용 -> close를 해야 함. 객체지향에서도 객체를 생성했다 하고 다 사용했다 하면 이렇게 릴리즈해줘야함.
대신 c#에서는 가비지콜렉터가 알아서 해주기 때문에 직접 구현은 하지 않지만, 원래 해줘야 함 .
https://dev.mysql.com/downloads/
MySQL :: MySQL Community Downloads
The world's most popular open source database Contact MySQL | Login | Register
dev.mysql.com

위 사이트에서 dll을 받을 수 있는데, 8.~버전(?)이 유니티 2020 2022 버전에서 오류가 난다고 한다.
유니티에서 이 커넥터 최신버전을 사용할 수 있게끔 업데이트가 안된다고 한다 (개발자 포럼)
https://timeboxstory.tistory.com/139 이 블로그에는 Connecter/NET을 다운로드하라한다 실제로 ODBC로 다운받아보니 Mysql.Data.dll파일 존재 x
https://downloads.mysql.com/archives/c-net/
나중에 웹사이트에서 커넥터 찾아서 dll다운받고자 할 때 버전에 대해 잘 알아보고 설치할 것.
지금은 커넥터 구버전 dll을 받아서 사용
PlayFab로그인, 회원가입 기능을 마리아 DB에 연결해보자

(추가해야될거) : 플레이팹 ID를 게임매니저의 필드로 선언해 넣고, DontDestroyonLoad적용해서 씬이 이동해도 유지되도록 해줘야 함
그리고 MariaDB에서 받은 유저 ID(res)를
<LoginMariaDB()>에서
GameObject.Find("GameManager").GetComponent<GameManager>().myGlobalPlayFabId = res.ToString(); 해주는것
이전에 구성했더 화면으로 로그인, 회원가입 모두 정상적으로 되고 유저 정보는 PlayFab에 정상적으로 표시된다.
아래에 PlayFab 구현문서와 위 화면까지 구현된 파일을 올려놨으니 다운로드 받으면 된다
https://github.com/zhun0922/PlayFabInit
GitHub - zhun0922/PlayFabInit: 플레이팹 초기_로그인,회원가입 베이스기능
플레이팹 초기_로그인,회원가입 베이스기능. Contribute to zhun0922/PlayFabInit development by creating an account on GitHub.
github.com

먼저 위의 dll파일을 Assets/Plugins 디렉토리 생성해서 넣어주고 PlayFab씬을 복사한다.
-> 오류발생
https://ckbcorp.tistory.com/1284
C# 에서 MariaDB 연결할 때, MySqlConnection.Open() System.InvalidCastException: Object cannot be cast from DBNull to other
오프라인에서 VS C# + MariaDB 를 돌려야 할 일이 있어서 이래저래 설치하고 Visual Studio , Maria DB, heidisql portable ( 윈도우용 MariaDB Client), Mysql Connector 6.5 를 설치하고 돌려봤는데, 빌드는 되는데 자꾸 DB
ckbcorp.tistory.com
결론 : MariaDB 10.9이하 쓰던가 mysqlConnector사용
10.6으로 받고
https://timeboxstory.tistory.com/139
[Unity] 유니티에서 Mysql, MariaDB 연동하고 조회하기
✔ Unity - Mysql, 마리아 DB 연동하기 mysql dll import , mysql select, update, insert MS-SQL은 유니티에 내장되어있어서 쓰기가 편한데 .. Mysql, Maria DB는 별도 DLL을 구해서 사용해야되니까 불편하당 ㅠ_ㅠ 유니티
timeboxstory.tistory.com
RegisterDB -> player테이블에 Insert -> LoginDB -> 데이터 가져오고, ID가져와서 GameManger필드에 넣어줌
-> 동시에 LoginToMariaDBLoginHistory()에서 LoginHistory테이블에 Insert로 데이터 넣는다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using MySql.Data.MySqlClient;
using MySql.Data;
using System;
using System.Data;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
public class LoginSignupMariaDBManager : MonoBehaviour
{
//private MySqlConnection connection;
private MySqlConnection myConnection = null;
private MySqlCommand myCommand = null;
private MySqlDataReader myDataReader = null;
public TMP_InputField inputUserID;
public TMP_InputField inputPassword;
public TMP_InputField inputEmail;
public TMP_Text displayMessage;
private string username;
private string password;
private string email;
//---------------------------------------------------
// Start is called before the first frame update
void Start()
{
SetupSQLConnection();
}
// Update is called once per frame
void Update()
{
}
//--------------------------
public void UsernameValueChanged()
{
username = inputUserID.text.ToString();
}
public void PasswordValueChanged()
{
password = inputPassword.text.ToString();
}
public void EmailValueChanged()
{
email = inputEmail.text.ToString();
}
//-------------------------- SQLConnect
private void SetupSQLConnection()
{
if (myConnection == null)
{
string connectionString =
"SERVER=61.245.246.242; Port=3308; " +
"DATABASE=metaverse; " +
"UID=wonkwangdc; " +
"PASSWORD=wkdc2017;";
try
{
myConnection = new MySqlConnection(connectionString);
//connection.Open();
Debug.Log("[MariaDB Connection] Connected successfully ..");
displayMessage.text = "[MariaDB Connection] Connected successfully ..";
}
catch (MySqlException ex)
{
Debug.LogError("[MariaDB Connection Error] " + ex.ToString());
displayMessage.text = "[MariaDB Connection Error] " + ex.ToString();
}
}
}
private bool CheckDataForMariaDB(int p)
{
if (p == 1) // Signup 일 때
{
Debug.Log("Signup [" + username + " " + password + " " + email + "]");
if ((username != null) && (password != null) && (email != null))
{
return true;
}
else
{
Debug.Log("[INPUT ERROR] User input has an ERROR (NOT Enough to signup)");
displayMessage.text = "[INPUT ERROR] User input has an ERROR (NOT Enough to signup)";
return false;
}
}
else if (p == 2) // Login 일 때
{
Debug.Log("Login [" + username + " " + password + "]");
if ((username != null) && (password != null))
{
return true;
}
else
{
Debug.Log("[INPUT ERROR] User login input has an ERROR (NOT Enough to login)");
displayMessage.text = "[INPUT ERROR] User login input has an ERROR (NOT Enough to login)";
return false;
}
}
else
{
return false;
}
}
// --------------------------------- SINGUP
public void RegisterMariaDB()
{
if (CheckDataForMariaDB(1))
{
Debug.Log("Signup is continued ..");
//RegisterUserToMariaDBPlayer();
if (RegisterUserToMariaDBPlayer())
{
inputUserID.text = "";
inputPassword.text = "";
inputEmail.text = "";
displayMessage.text = "Ok, 정상적으로 회원가입되었습니다.";
Debug.Log("Ok, 정상적으로 회원가입되었습니다.");
}
}
else
{
displayMessage.text = "[ERROR] Error is occurred during your register ..";
Debug.LogError("[ERROR] Error is occurred during your register ..");
}
}
private bool RegisterUserToMariaDBPlayer()
{
string currentDateTimeValue = "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
string usernameValue = "'" + username + "'";
string passwordValue = "'" + password + "'";
string emailValue = "'" + email + "'";
//string commandText = string.Format("INSERT INTO daily_log (username, user_id) VALUES ({0}, {1})", "'megaplayer'", 10);
string commandText = string.Format(
"INSERT INTO player " +
"(username, password, email, confirmationdate) " +
"VALUES ({0}, {1}, {2}, {3})",
usernameValue, passwordValue, emailValue, currentDateTimeValue
);
Debug.Log(commandText);
if (myConnection != null)
{
//MySqlCommand command = connection.CreateCommand();
//command.CommandText = commandText;
myCommand = myConnection.CreateCommand();
myCommand.CommandText = commandText;
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
return true;
}
catch (System.Exception ex)
{
displayMessage.text = "[MariaDB SQL Error] " + ex.ToString();
Debug.LogError("[MariaDB SQL Error] " + ex.ToString());
return false;
}
}
else
{
displayMessage.text = "[MariaDB Error] Connection error ..";
Debug.LogError("[MariaDB Error] Connection error ..");
return false;
}
}
//----------------------------- LOGIN
public void LoginMariaDB()
{
if (CheckDataForMariaDB(2))
{
Debug.Log("Login is continued ..");
int res = LoginToMariaDBPlayer(); //playerID반환 유저가 아무도 없다면 -1 반환
if (res > 0)
{
GameObject.Find("GameManager").GetComponent<GameManager>().myGlobalPlayFabId = res.ToString();
LoginToMariaDBLoginHistory(res);
}
else
{
displayMessage.text = "[" + res + "] Login failed ...";
Debug.Log("[" + res + "] Login failed ...");
inputUserID.text = "";
inputPassword.text = "";
}
}
else
{
displayMessage.text = "[ERROR] Error is occurred during your login ..";
Debug.LogError("[ERROR] Error is occurred during your login ..");
}
}
//private DataTable LoginToMariaDBPlayer()
private int LoginToMariaDBPlayer()
{
//DataTable dt = new DataTable();
string commandTextSelect = string.Format(
"SELECT * FROM player WHERE username='" + username + "' AND password='" + password + "'"
);
Debug.Log(commandTextSelect);
myConnection.Open(); //데이터 오픈
//MySqlDataAdapter adapter = new MySqlDataAdapter(commandTextSelect, myConnection); //어댑터 만든 다음
//adapter.Fill(dt); //Fill시켜야 하는데, 요즘 리더에서 이 기능을 다 해주는 느낌이라 주석처리
myCommand = new MySqlCommand(commandTextSelect, myConnection);
myDataReader = myCommand.ExecuteReader();
int playerID = -1; //데이터가 없는것
while (myDataReader.Read()) //데이터가 여러개있기 때문에 반복해서 접근
{
Debug.Log(myDataReader[0] + "-" + myDataReader[1] + "-" + myDataReader[3] + "-" + myDataReader[6]);
playerID = (int)myDataReader[0]; //ID(key)는 하나씩 증가, 14번째 회원가입 한 유저는 ID 14.
}
myConnection.Close();
//return dt;
return playerID;
}
private void LoginToMariaDBLoginHistory(int id)
{
//다른 테이블인 LoginHistory테이블에 데이터 넣어주는것
string currentDateTimeValue = "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
string usernameValue = "'" + username + "'";
string commandText = string.Format(
"INSERT INTO login_history (player_id, login_time) " +
"VALUES ({0}, {1})",
id, currentDateTimeValue
);
Debug.Log(commandText);
if (myConnection != null)
{
myCommand = myConnection.CreateCommand();
myCommand.CommandText = commandText;
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
StartGame();
}
catch (System.Exception ex)
{
displayMessage.text = "[MariaDB SQL Error] " + ex.ToString();
Debug.LogError("[MariaDB SQL Error] " + ex.ToString());
}
}
else
{
displayMessage.text = "[MariaDB Error] Connection error ..";
Debug.LogError("[MariaDB Error] Connection error ..");
}
}
//------------------- Game Start !
void StartGame()
{
displayMessage.text = "Now, start the game, enjoy it";
Debug.Log("Now, start the game, enjoy it");
}
}