public void test_bind_parameter_index() { using (sqlite3 db = ugly.open(":memory:")) { db.exec("CREATE TABLE foo (x int, v int, t text, d real, b blob, q blob);"); using (sqlite3_stmt stmt = db.prepare("INSERT INTO foo (x,v,t,d,b,q) VALUES (:x,:v,:t,:d,:b,:q)")) { Assert.IsTrue(stmt.stmt_readonly() == 0); Assert.AreEqual(stmt.bind_parameter_count(), 6); Assert.AreEqual(stmt.bind_parameter_index(":m"), 0); Assert.AreEqual(stmt.bind_parameter_index(":x"), 1); Assert.AreEqual(stmt.bind_parameter_index(":v"), 2); Assert.AreEqual(stmt.bind_parameter_index(":t"), 3); Assert.AreEqual(stmt.bind_parameter_index(":d"), 4); Assert.AreEqual(stmt.bind_parameter_index(":b"), 5); Assert.AreEqual(stmt.bind_parameter_index(":q"), 6); Assert.AreEqual(stmt.bind_parameter_name(1), ":x"); Assert.AreEqual(stmt.bind_parameter_name(2), ":v"); Assert.AreEqual(stmt.bind_parameter_name(3), ":t"); Assert.AreEqual(stmt.bind_parameter_name(4), ":d"); Assert.AreEqual(stmt.bind_parameter_name(5), ":b"); Assert.AreEqual(stmt.bind_parameter_name(6), ":q"); } } }
public static void bind(this sqlite3_stmt stmt, params object[] a) { if (a == null) { return; } int count = Math.Min(stmt.bind_parameter_count(), a.Length); // TODO instead of Math.Min(), consider comparing the two // counts and throwing if they're not equal. for (int i = 0; i < count; i++) { int ndx = i + 1; if (a[i] == null) { //Console.WriteLine("bind: {0} null", i); stmt.bind_null(ndx); } else { Type t = a[i].GetType(); //Console.WriteLine("bind: {0} {1} -- {2}", i, t, a[i]); if (typeof(String) == t) { stmt.bind_text(ndx, (string)a[i]); } else if ( (typeof(Int32) == t) || (typeof(Boolean) == t) || (typeof(Byte) == t) || (typeof(UInt16) == t) || (typeof(Int16) == t) || (typeof(sbyte) == t) || (typeof(Int64) == t) || (typeof(UInt32) == t) ) { stmt.bind_int64(ndx, (long)(Convert.ChangeType(a[i], typeof(long), null))); } else if ( (typeof(double) == t) || (typeof(float) == t) || (typeof(decimal) == t) ) { stmt.bind_double(ndx, (double)(Convert.ChangeType(a[i], typeof(double), null))); } else if (typeof(DateTime) == t) { DateTime d = (DateTime)a[i]; DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); TimeSpan diff = d.ToUniversalTime() - origin; stmt.bind_int64(ndx, (long)diff.TotalSeconds); } else if (typeof(byte[]) == t) { stmt.bind_blob(ndx, (byte[])a[i]); } else { throw new NotSupportedException("Invalid type conversion" + t); } } } }