首页 > 解决方案 > 如何将整数列表添加到 sqlite3 的表中

问题描述

我正在编写一个将用于游戏的数据库。因此,在这个数据库中,我有一个PLAYERS表格,其中包含有关游戏玩家的一些信息。对于该表的其中一列,我需要一个列表,其中包含与当前玩家为友的玩家的整数 (ID)。(就像一个朋友列表)
问题是首先这个列表的大小没有定义并且会改变(通过添加或删除一个朋友),第二个问题是 sqlite3 只允许使用主要值,如 INT、TEXT 等。所以我的问题是,我如何在我的表中添加这样的列并相应地修改它(意味着从中添加或删除内容)?
我通过搜索知道我可以添加第二个表并使用它,但我真的不知道该怎么做,如果有人可以帮助并指导我扔它,我将不胜感激。
这是一些代码:

  std::string sql = "CREATE TABLE IF NOT EXISTS PLAYERS("
                    "ID INTEGER PRIMARY KEY AUTOINCREMENT, "
                    "USERNAME               TEXT NOT NULL UNIQUE, " 
                    "PASSWORD               TEXT NOT NULL, "
                    "SCORE                  REAL NOT NULL  );"; 
  // here I want to add the column that I am talking about with name of FRIENDS which contains the ID (a list of integers) of the other players
  int ret = 0;
  char* errMsg;

  ret = sqlite3_exec(DB, sql.c_str(), nullptr, 0, &errMsg);
  if (ret != SQLITE_OK) {
    std::cerr << "Table creation error: " << sqlite3_errmsg(DB) << std::endl;
    sqlite3_free(errMsg);
    return false;
  } else {
    std::cout << "Table created successfully." << std::endl;
  }

  std::ostringstream osql;
  osql << "INSERT INTO PLAYERS (USERNAME, PASSWORD, SCORE) VALUES('" << "mra" << "', '" << "12456" << "', " << 20.2 << ");";
  std::string sql = osql.str();

  int ret = 0;
  char* errMsg;

  ret = sqlite3_exec(DB, sql.c_str(), nullptr, 0, &errMsg);
  if (ret != SQLITE_OK) {
    std::cerr << "Insertion error: " << sqlite3_errmsg(DB) << std::endl;
    sqlite3_free(errMsg);
    return false;
  } else {
    std::cout << "Insertion was successfull." << std::endl;
  }

提前感谢您的帮助。

标签: c++databasesqlite

解决方案


您所描述的是玩家之间的多对多关系。与朋友列表的列相比,连接表更适合此目的。

联结表可以具有如下结构:

| Player1 | Player2 |
| 1       | 2       |
| 1       | 3       |

使用 CHECK 约束,您可以强制执行 Player1 < Player2,从而消除重复友谊关系的可能性。

创建这样一个表 ( FRIENDS) 的 sql 将是:

CREATE TABLE "FRIENDS" (
    "PLAYER1"   INTEGER,
    "PLAYER2"   INTEGER,
    CHECK(PLAYER1<PLAYER2),
    FOREIGN KEY("PLAYER1") REFERENCES "PLAYERS"("ID") ON DELETE CASCADE,
    PRIMARY KEY("PLAYER1","PLAYER2"),
    FOREIGN KEY("PLAYER2") REFERENCES "PLAYERS"("ID") ON DELETE CASCADE
);

ON DELETE CASCADE确保当表中的主键与PLAYERS表中的相关行FRIENDS也被删除时。

所以你只需要查询FRIENDS表来获取玩家的朋友。


推荐阅读