zoukankan      html  css  js  c++  java
  • 【SQLite】SQLite中DateTime类型字段存取问题

    1、如果直接存储DateTime.ToString()或DateTime.ToString("yy/MM/dd hh:mm:ss")(写DateTime.ToString("yy-MM-dd hh:mm:ss")会插入数据不成功),能成功插入数据并在SqliteDeveloper中显示正确时间,但从数据库查询时,会报错。

    2、用DateTime.ToString("s")插入数据,能成功插入数据,但在SqliteDeveloper中全都显示1899/12/30,从数据库查询时,不会报错。

    3、有人说把数据类型设为nvarchar。这样可以成功插入数据并读取,但碰到要用时间作为查询条件时,无法实现功能。可以看看这个帖子:https://bbs.csdn.net/topics/390302153

    无奈只能选第二种方式。这问题也是蛮坑的。

    -----------------更新-----------------

    无语了,本来用DateTime.ToString("s")已经测试可以了,不知怎么的今天又发现还是提示无效的DateTime。
    又是一通搜索。
    原来只能用参数化的方式插入/修改数据,用sql拼接语句就不行。


    Sqlite参数化查询:
    https://www.cnblogs.com/kdp0213/p/8554032.html

    我自己写的代码:

            /// <summary>
            /// 指定列插入数据
            /// </summary>
            public bool AddDatas1<T>(T testClass, string tableName)
            {
                string colStr = "";
                string tmpValueStr = "";
    
                Type t = testClass.GetType();//获得该类的Type
                foreach (PropertyInfo pi in t.GetProperties())
                {
                    string name = pi.Name;
                    if (name.ToLower() == "id")
                    {
                        continue;
                    }
                    colStr += pi.Name + ",";
                    tmpValueStr += "@" + pi.Name + ",";
                }
                colStr = colStr.Substring(0, colStr.LastIndexOf(',')); //删掉最后一个逗号
                tmpValueStr = tmpValueStr.Substring(0, tmpValueStr.LastIndexOf(','));
    
                string cmdStr = string.Format("insert into {0}({1}) values({2});", tableName, colStr, tmpValueStr);
    
                try
                {
                    using (SQLiteCommand cmd = new SQLiteCommand(cmdStr, SQL_Conn))
                    {
                        foreach (PropertyInfo pi in t.GetProperties())
                        {
                            string name = pi.Name;
                            if (name.ToLower() == "id")
                            {
                                continue;
                            }
    
                            DbType DBtype = DbType.String;
                            Type type = pi.PropertyType;
                            object value = pi.GetValue(testClass, null);//用GetValue获得值
    
                            if (type == typeof(DateTime))
                            {
                                DBtype = DbType.DateTime;
                            }
                            else if (type == typeof(bool))
                            {
                                DBtype = DbType.Boolean;
                                value = (((bool)value == true) ? 1 : 0);
                            }
                            else if (type == typeof(int))
                            {
                                DBtype = DbType.Int32;
                            }
    
                            if (value == null)
                            {
                                value = DBNull.Value;
                            }
                            cmd.Parameters.Add("@" + name, DBtype);//添加参数
                            cmd.Parameters["@" + name].Value = value;//为参数赋值
                        }
                        cmd.ExecuteNonQuery();
                        return true;
                    }
                }
                catch(Exception ex)
                {
                    return false;
                }
            }
            /// <summary>
            /// 修改整条数据
            /// </summary>
            /// <param name="testClass">类的实例</param>
            /// <param name="tableName">表名</param>
            /// <param name="mainKeyName">主键名</param>
            /// <param name="keyValue">主键值</param>
            /// <returns></returns>
            public bool ModifyData1<T>(T testClass, string tableName, string mainKeyName, string keyValue)
            {
                string colStr = "";
                string valueStr = "";
    
                Type t = testClass.GetType();//获得该类的Type
                foreach (PropertyInfo pi in t.GetProperties())
                {
                    string name = pi.Name;
                    if (name.ToLower() == "id")
                    {
                        continue;
                    }
                    if (name == mainKeyName) //如果索引的键是字符串类型
                    {
                        Type type = pi.PropertyType;
                        if (type == typeof(string))
                        {
                            keyValue = "'" + keyValue + "'";//如果索引的键是字符串类型 加上引号
                        }
                    }
                    colStr += pi.Name + "=@" + pi.Name + ",";
                }
                colStr = colStr.Substring(0, colStr.LastIndexOf(',')); //删掉最后一个逗号
                string cmdStr = string.Format("update {0} set {1} where {2}" + " = " + "{3};", tableName, colStr, mainKeyName, keyValue);
              
                try
                {
                    using (SQLiteCommand cmd = new SQLiteCommand(cmdStr, SQL_Conn))
                    {
                        foreach (PropertyInfo pi in t.GetProperties())
                        {
                            string name = pi.Name;
                            if (name.ToLower() == "id")
                            {
                                continue;
                            }
    
                            DbType DBtype = DbType.String;
                            Type type = pi.PropertyType;
                            object value = pi.GetValue(testClass, null);//用GetValue获得值
    
                            if (type == typeof(DateTime))
                            {
                                DBtype = DbType.DateTime;
                            }
                            else if (type == typeof(bool))
                            {
                                DBtype = DbType.Boolean;
                                value = (((bool)value == true) ? 1 : 0);
                            }
                            else if (type == typeof(int))
                            {
                                DBtype = DbType.Int32;
                            }
    
                            if (value == null)
                            {
                                value = DBNull.Value;
                            }
                            cmd.Parameters.Add("@" + name, DBtype);  //添加参数
                            cmd.Parameters["@" + name].Value = value;//为参数赋值
                        }
                        cmd.ExecuteNonQuery();
                        return true;
                    }
                }
                catch(Exception ex)
                {
                    return false;
                }
            }

    如果插入数据需要返回自增ID:

            /// <summary>
            /// 指定列插入数据并获取自增长主键值
            /// </summary>
            public bool AddDatas<T>(T testClass, string tableName, out int id)
            {
                string colStr = "";
                string tmpValueStr = "";
                id = 0;
                Type t = testClass.GetType();//获得该类的Type
                foreach (PropertyInfo pi in t.GetProperties())
                {
                    string name = pi.Name;
                    if (name.ToLower() == "id")//主表主键不赋值
                    {
                        continue;
                    }
                    colStr += pi.Name + ",";
                    tmpValueStr += "@" + pi.Name + ",";
                }
                colStr = colStr.Substring(0, colStr.LastIndexOf(',')); //删掉最后一个逗号
                tmpValueStr = tmpValueStr.Substring(0, tmpValueStr.LastIndexOf(','));
    
                string cmdStr = string.Format("insert into {0}({1}) values({2});" + "select last_insert_rowid() from {0};", tableName, colStr, tmpValueStr);
    
                try
                {
                    using (SQLiteCommand cmd = new SQLiteCommand(cmdStr, SQL_Conn))
                    {
                        foreach (PropertyInfo pi in t.GetProperties())
                        {
                            string name = pi.Name;
                            if (name.ToLower() == "id")
                            {
                                continue;
                            }
    
                            DbType DBtype = DbType.String;
                            Type type = pi.PropertyType;
                            object value = pi.GetValue(testClass, null);//用GetValue获得值
    
                            if (type == typeof(DateTime))
                            {
                                DBtype = DbType.DateTime;
                            }
                            else if (type == typeof(bool))
                            {
                                DBtype = DbType.Boolean;
                                value = (((bool)value == true) ? 1 : 0);
                            }
                            else if (type == typeof(int))
                            {
                                DBtype = DbType.Int32;
                            }
    
                            if (value == null)
                            {
                                value = DBNull.Value;
                            }
                            cmd.Parameters.Add("@" + name, DBtype);  //添加参数
                            cmd.Parameters["@" + name].Value = value;//为参数赋值
                        }
                        DbDataReader reader = cmd.ExecuteReader();
                        if (reader.Read())
                        {
                            id = int.Parse(reader[0].ToString());
                            reader.Close();
                            return true;
                        }
                        else
                        {
                            id = 0;
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
    /*******相与枕藉乎舟中,不知东方之既白*******/
  • 相关阅读:
    ios开发中的基本设计模式
    Swift进阶
    转帖:深入理解JavaScript系列
    触摸事件、手势识别、摇晃事件、耳机线控
    打造自己的“美图秀秀”
    地图与定位
    python 深拷贝,浅拷贝
    Django 路由(SimpleRouter, DefaultRouter,ExtendedDefaultRouter)
    Django 国际化(翻译)
    wkhtmltopdf 转换后 表格不显示 python解决方案
  • 原文地址:https://www.cnblogs.com/Mars-0603/p/14632883.html
Copyright © 2011-2022 走看看