示例#1
0
        /// <summary>
        /// 创建数据表
        /// </summary>
        /// <param name="table"></param>
        public void CreateTable(SQLiteTable table)
        {
            StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("create table if not exists `");
            sb.Append(table.TableName);
            sb.AppendLine("`(");
            bool firstRecord = true;

            foreach (SQLiteColumn col in table.Columns)
            {
                if (col.ColumnName.Trim().Length == 0)
                {
                    throw new Exception("Column name cannot be blank.");
                }

                if (firstRecord)
                {
                    firstRecord = false;
                }
                else
                {
                    sb.AppendLine(",");
                }

                sb.Append(col.ColumnName);
                sb.Append(" ");

                if (col.AutoIncrement)
                {
                    sb.Append("integer primary key autoincrement");
                    continue;
                }

                switch (col.ColDataType)
                {
                case ColType.Text:
                    sb.Append("text"); break;

                case ColType.Integer:
                    sb.Append("integer"); break;

                case ColType.Decimal:
                    sb.Append("decimal"); break;

                case ColType.DateTime:
                    sb.Append("datetime"); break;

                case ColType.BLOB:
                    sb.Append("blob"); break;
                }

                if (col.PrimaryKey)
                {
                    sb.Append(" primary key");
                }
                else if (col.NotNull)
                {
                    sb.Append(" not null");
                }
                else if (col.DefaultValue.Length > 0)
                {
                    sb.Append(" default ");

                    if (col.DefaultValue.Contains(" ") || col.ColDataType == ColType.Text || col.ColDataType == ColType.DateTime)
                    {
                        sb.Append("'");
                        sb.Append(col.DefaultValue);
                        sb.Append("'");
                    }
                    else
                    {
                        sb.Append(col.DefaultValue);
                    }
                }
            }

            sb.AppendLine(");");

            cmd.CommandText = sb.ToString();
            cmd.ExecuteNonQuery();
        }