返回

用简练代码实现对SQLite数据库的读写和兼容安卓端的策略

Android

在 Godot Mono 中使用 SQLite 数据库:一份兼容安卓端的 C# 脚本

概要

SQLite 是一款轻量级且高效的数据库,在各种应用程序中得到广泛应用。如果您正在使用 Godot Mono 作为您的游戏引擎,并且希望将 SQLite 数据库集成到您的项目中,那么这篇博客将为您提供一个简洁高效的解决方案。这份 C# 脚本不仅易于使用,还具有安卓端兼容性,让您的程序可以在不同的平台上无缝运行。

使用说明

要使用这份 C# 脚本,请按照以下步骤操作:

  1. 在 Godot Mono 中创建一个新的 C# 脚本文件,将其命名为 "SQLiteManager.cs"。
  2. 将以下代码复制并粘贴到脚本文件中:
using System;
using System.Collections.Generic;
using System.IO;
using Godot;
using Mono.Data.Sqlite;

public class SQLiteManager : Node
{
    private SqliteConnection _connection;
    private string _databasePath;

    public override void _Ready()
    {
        _databasePath = "res://path/to/your/database.db";
        ConnectToDatabase();
    }

    public void ConnectToDatabase()
    {
        try
        {
            _connection = new SqliteConnection(
using System;
using System.Collections.Generic;
using System.IO;
using Godot;
using Mono.Data.Sqlite;

public class SQLiteManager : Node
{
    private SqliteConnection _connection;
    private string _databasePath;

    public override void _Ready()
    {
        _databasePath = "res://path/to/your/database.db";
        ConnectToDatabase();
    }

    public void ConnectToDatabase()
    {
        try
        {
            _connection = new SqliteConnection($"Data Source={_databasePath}");
            _connection.Open();
        }
        catch (Exception ex)
        {
            GD.Print("Error connecting to database: " + ex.Message);
        }
    }

    public void CreateTable()
    {
        try
        {
            using (var command = _connection.CreateCommand())
            {
                command.CommandText = "CREATE TABLE IF NOT EXISTS [table_name] (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)";
                command.ExecuteNonQuery();
            }
        }
        catch (Exception ex)
        {
            GD.Print("Error creating table: " + ex.Message);
        }
    }

    public void InsertData(string name, int score)
    {
        try
        {
            using (var command = _connection.CreateCommand())
            {
                command.CommandText = "INSERT INTO [table_name] (name, score) VALUES (@name, @score)";
                command.Parameters.AddWithValue("@name", name);
                command.Parameters.AddWithValue("@score", score);
                command.ExecuteNonQuery();
            }
        }
        catch (Exception ex)
        {
            GD.Print("Error inserting data: " + ex.Message);
        }
    }

    public List<Dictionary<string, object>> SelectData()
    {
        try
        {
            using (var command = _connection.CreateCommand())
            {
                command.CommandText = "SELECT * FROM [table_name]";
                using (var reader = command.ExecuteReader())
                {
                    var results = new List<Dictionary<string, object>>();
                    while (reader.Read())
                    {
                        var row = new Dictionary<string, object>();
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            row.Add(reader.GetName(i), reader[i]);
                        }
                        results.Add(row);
                    }
                    return results;
                }
            }
        }
        catch (Exception ex)
        {
            GD.Print("Error selecting data: " + ex.Message);
        }

        return null;
    }

    public void CloseConnection()
    {
        if (_connection != null)
        {
            _connection.Close();
            _connection = null;
        }
    }

    public override void _ExitTree()
    {
        CloseConnection();
    }
}
quot;Data Source={_databasePath}"
); _connection.Open(); } catch (Exception ex) { GD.Print("Error connecting to database: " + ex.Message); } } public void CreateTable() { try { using (var command = _connection.CreateCommand()) { command.CommandText = "CREATE TABLE IF NOT EXISTS [table_name] (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)"; command.ExecuteNonQuery(); } } catch (Exception ex) { GD.Print("Error creating table: " + ex.Message); } } public void InsertData(string name, int score) { try { using (var command = _connection.CreateCommand()) { command.CommandText = "INSERT INTO [table_name] (name, score) VALUES (@name, @score)"; command.Parameters.AddWithValue("@name", name); command.Parameters.AddWithValue("@score", score); command.ExecuteNonQuery(); } } catch (Exception ex) { GD.Print("Error inserting data: " + ex.Message); } } public List<Dictionary<string, object>> SelectData() { try { using (var command = _connection.CreateCommand()) { command.CommandText = "SELECT * FROM [table_name]"; using (var reader = command.ExecuteReader()) { var results = new List<Dictionary<string, object>>(); while (reader.Read()) { var row = new Dictionary<string, object>(); for (int i = 0; i < reader.FieldCount; i++) { row.Add(reader.GetName(i), reader[i]); } results.Add(row); } return results; } } } catch (Exception ex) { GD.Print("Error selecting data: " + ex.Message); } return null; } public void CloseConnection() { if (_connection != null) { _connection.Close(); _connection = null; } } public override void _ExitTree() { CloseConnection(); } }

使用示例

要在您的场景中使用此脚本:

  1. 创建一个 SQLiteManager 节点。
  2. 使用脚本调用数据库操作方法。

例如,要创建表,请使用以下代码:

var sqliteManager = GetNode<SQLiteManager>("SQLiteManager");
sqliteManager.CreateTable();

安卓端兼容性

要确保您的应用程序在安卓端兼容,请在构建项目时勾选 "Android Export" 选项。此外,您需要在安卓设备上安装 SQLite 库。

结论

这份 C# 脚本为您提供了一种简单而强大的方式,可以在 Godot Mono 中使用 SQLite 数据库。借助其对安卓端的兼容性,您可以轻松地将 SQLite 数据库集成到您的跨平台应用程序中。通过遵循本文提供的说明,您可以开始使用 SQLite 数据库来存储和管理您的数据,提升您的项目开发体验。

常见问题解答

1. 如何从数据库中选择数据?

使用 SelectData() 方法从数据库中选择数据。此方法返回一个字典列表,其中包含表中的所有行和列。

2. 如何插入数据到数据库中?

使用 InsertData() 方法将数据插入数据库。此方法需要两个参数:要插入的名称和分数。

3. 如何连接到数据库?

使用 ConnectToDatabase() 方法连接到数据库。此方法负责打开与数据库的连接。

4. 如何关闭与数据库的连接?

使用 CloseConnection() 方法关闭与数据库的连接。

5. 如何在场景退出时关闭与数据库的连接?

在 _ExitTree() 方法中关闭与数据库的连接。