I've never attempted to store any objects in my SQLite database and doing some searching on the subject didn't help. I'm using VS 2012, the NuGet SQLite DLLs, and C# with .NET 4.5.
Here are the available data types I can see and presumably, use: integer, int, smallint, tinyint, bigint, bit, varchar(50), nvarchar(50), text, ntext, image, money, float, real, decimal, numeric(18,0), char(10), nchar(10), datetime, guid.
I have graph points (x, y) that I must store for each graph. There are a variable amount. I store the values into an ArrayList currently and am having a hard time trying to figure out how to store them...
If I create a dedicated table just for each graph that stores all it's (x, y) points, how do I specify a variable amount of (x, y) coordinates to save within the graph table? Is there an easier way using some third party library? Can anyone else think of another simpler solution perhaps using the technology I currently have available?
Thanks!
2 Answers 2
You could serialize the object as suggested - though that kind of kills the point of a relational database.
Or you can use a DB relation.
Graph
-id integer
-varchar(50) name
GraphPoints
-GraphID int FK to Graph
-x int
-y int
Then just join the two, and you can get all points for the table:
SELECT * FROM Graph g INNER JOIN GraphPoints gp on g.id = gp.GraphID
WHERE g.id = somegraphid
4 Comments
I ended up using JSON since it was much easier to manage and far less code than creating an entire table just for my graph coordinates, this seemed to be the best route for my situation. Hopefully this helps someone in the future!
[Serializable]
public class Coordinate
{
public string x { get; set; }
public string y { get; set; }
public Coordinate() {}
}
public class CoordinateList
{
public List<Coordinate> Coordinate { get; set; }
}
And here's a simple working example on how to create and serialize the above class into a JSON string you can store as a TEXT or VARCHAR type in SQLite 3. Also included is how to deserialize.
CoordinateList list = new CoordinateList();
list.Coordinate = new List<Coordinate>();
Coordinate cord = new Coordinate();
cord.x = "1";
cord.y = "10";
list.Coordinate.Add(cord);
list.Coordinate.Add(cord);
list.Coordinate.Add(cord);
JavaScriptSerializer serializer = new JavaScriptSerializer();
String jsonStr = serializer.Serialize(list);
MessageBox.Show("json:" + jsonStr);
list = serializer.Deserialize<CoordinateList>(jsonStr);
foreach (Coordinate c in list.Coordinate)
{
MessageBox.Show("x: " + c.x + ", y: " + c.y);
}
P.S. The JavaScriptSerializer is included in the System.Web.Extentions reference. I was looking for the System.Web.Script.Serialization namespace forever and couldn't find it.
Special thanks to these ridiculously hard to find links:
varchar(MAX)
) field if it doesn't make sense to store each one as a record in its own table.