创建数据库连接代码
using UnityEngine;
using MySql.Data.MySqlClient;
using System.Data;
public class DatabaseManager : MonoBehaviour
{
private string connectionString = "server=localhost;port=3306;database=game_db;user=root;password=root;";
void Start()
{
// 测试连接
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
try
{
connection.Open();
Debug.Log("数据库连接成功!");
}
catch (System.Exception e)
{
Debug.LogError("数据库连接失败: " + e.Message);
}
}
}
public void InsertData(string playerName, int score)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO player_scores (player_name, score) VALUES (@playerName, @score)";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@playerName", playerName);
command.Parameters.AddWithValue("@score", score);
command.ExecuteNonQuery();
}
}
}
}
游戏中调用
public class GameLogic : MonoBehaviour
{
public DatabaseManager databaseManager;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
// 假设玩家按空格键完成操作,存储数据到数据库
databaseManager.InsertData("Player1", 100);
}
}
}