sqlite (.db) database with monogame

Hi
I have a game with a sqlite database (namedb.db) and can’t open the file
Is there a sample?

Hey @RuiM, welcome to the forums! :slight_smile:

MonoGame has no special support for databases, so I don’t think this is the best place to look for support. With a quick google search for using SQLite in .NET I found the sqlite-net project on GitHub, that might be useful.

1 Like

One of the nice things about MonoGame is that you can use all the work that’s been done for Xamarin and the entire .Net ecosystem. Using sqlite in MonoGame is super powerful once you have it setup, but it is a little bit more work than just opening a file. I wrote a nuget package that sits on top on sqlite-net and helps create the connection:


sample app:

And a blog post (a bit out of date, the names of all the sqlite-net packages have changed):

Hope this helps. Cheers!

1 Like

Hi
I also can’t use System.IO.FileStream
My project is targeting .NET for Windows Store Apps (Windows 8.1)

And can’t link to .NET Framework Version 4.6

When trying to install I got this message:
Install-Package : Could not install package ‘System.IO.FileSystem 4.3.0’. You are trying to install this package into a project that targets ‘.NETCore,Version=v4.5.1’, but the
package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

Thanks.
I will try this and then let you know

Why!?

EDIT

Oh, forgot to say, you have to target 4.5 I think…

1 Like

Yes… but the model of the app is this and this app doesn’t allow me to change the target…

I need to create again the project, what is the monogame type of project you suggest in order to make possible to use, for example, System.IO.FileStream ?

What file are you attempting to open?

UWP does not support FileStream and uses another method, If I recall…

Explain your intention so we can advise further…

On new project select .NET 4.5 at the top, also upgrade to Windows 10, Windows 8.1 is no longer supported mainstream: https://support.microsoft.com/en-us/help/13853/windows-lifecycle-fact-sheet

You can still upgrade for free, look around to find out how in your country for more relevant data…

EDIT

Hopefully this puts you in the right direction for now:

Why not use loading and saving serialization like user preference file

You need System:IO

Remember prepare serialization object like this

[Serializable]
class PreferenceObject
{
    public int score;
    public int[] lastscones;
    ....
}

Or you can use https://msdn.microsoft.com/en-us/library/ms973893.aspx

If you have problem than you need to use with WinForms because WinForms has generating user preference saver / loader

I already have windows 10.
I only want to open a txt file with the following info:
name of player, time to hit a certain object, and other object
then compute a mean of times for the final game after more than one game.

And yes it is a UWP. So I need to read and write to a txt file or use an sqlite database but I think a txt file is perfect to this simple purpose.

Thanks. Never thought about using serialization but will also try this.

1 Like

Just you check if you want create simple game launcher with current passing arguments than you understand how does gsme launcher

Example 640 x 480 is default size of game launcher. If you set up with arguments for example .w 1200 .h 720 than you exit game launcher and you forget to set up width and height and you run game launcher- what does it happen? This game launcher has saved size after passing arguments like 1200 x 720. It is easy trick like “user preference”

Check the Links and also look at LINQ to SQL https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/

I recommend you if you want get real serialization like example my own FileSerializer.cs

I will tell you how do you know like game window width and height for example:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace MonoGameHL.Preferences
{
    public class FileSerializer
    {
        private static string saveToDir = Environment.CurrentDirectory;

        public static Object ReadFromObject(string path)
        {
            Object obj;
            string pathToPref = Path.Combine(saveToDir, path);
            if (File.Exists(pathToPref))
            {
                IFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream(pathToPref, FileMode.Open, FileAccess.Read, FileShare.Read);
                obj = formatter.Deserialize(stream);
                stream.Close();
            }
            else
            {
                return null;
            }

            return obj;
        }

        public static void WriteToObject(string path, Object obj)
        {
            string pathToPref = Path.Combine(saveToDir, path);
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(pathToPref, FileMode.Create, FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, obj);
            stream.Close();
        }
    }
}

UserPref.cs

using System;

namespace MonoGameHL.Preferences
{
    [Serializable]
    public class UserPref
    {
        public int appWidth;
        public int appHeight;
        .... // for other important public variables like you want save score, endscores...
    }
}

Game1:
sometimes variables and In method public Game1

UserPref up;

public Game1()
{
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";

     if (File.Exists("pref.up"))
    {
        up = (UserPref)FileSerializer.ReadFromObject("pref.up");
        graphics.PreferredBackBufferWidth = up.appWidth;
        graphics.PreferredBackBufferHeight = up.appHeight;
    }
    else
    {
        up = new UserPref();
    }
}

And create protected override onExiting

protected override void OnExiting(object sender, EventArgs args)
{
    up = new UserPref();
    up.appWidth = graphics.PreferredBackBufferWidth;
    up.appHeight = graphics.PreferredBackBufferHeight;
    FileSerializer.WriteToObject("pref.up", up);
    base.OnExiting(sender, args);
}

And add new advanced mode of game launcher like any game have passing arguments:

public void ParseWithArguments(string[] args)
{
    for ( int i = 0; i < args.Length; i++)
    {
        switch(args[i])
        {
            case "-w":
            case "-width":
                graphics.PreferredBackBufferWidth = int.Parse(args[++i]);
                break;

            case "-h":
            case "-height":
                graphics.PreferredBackBufferHeight = int.Parse(args[++i]);
                break;
        }
    }
}

And Program.cs
Find:

[STAThread]
static void Main(string[] args)
{
    using (var game = new Game1())
        game.Run();
}

Replace with:

[STAThread]
static void Main(string[] args)
{
    using (var game = new Game1())
    {
        game.ParseWithArguments(args);
        game.Run();
    }
}

And make sure save and build than you can open command yourgame.exe -w 1000 -h 600 than it will save and exit than you can re open without command than you see that.

It is really easy.

But less problem like Window.Title can’t load string from pref.up if you see Title. I already tried. No success…

If your game loads and saves score file - you use override methods Initalize and Update.

I hope my nice solution helps you.

1 Like