SQLite修改表 字段的数据类型

首次发布:2018-05-04

方法一(推荐使用方法一)

以下是核心代码,直接调用下面方法即可以修改字段类型

/// <summary>
/// 修改SQLite表中指定列的数据类型
/// </summary>
/// <param name="ConnectionString">SQLite数据库存连接地址</param>
/// <param name="tableName">表名</param>
/// <param name="columnName">要修改的列名</param>
/// <param name="newDataType">新的数据类型(如INTEGER, TEXT, REAL等)</param>
public bool ChangeColumnType(string ConnectionString, string tableName, string columnName, string newDataType)
{
    // 临时列名,用于过渡
    string tempColumnName = $"temp_{columnName}_{Guid.NewGuid().ToString("N").Substring(0, 8)}";

    using (var connection = new SQLiteConnection(ConnectionString))
    {
        connection.Open();

        // 使用事务确保操作的原子性
        using (var transaction = connection.BeginTransaction())
        {
            try
            {
                // 1. 添加临时列(新数据类型)
                using (var cmd = new SQLiteCommand(connection))
                {
                    cmd.Transaction = transaction;
                    cmd.CommandText = $"ALTER TABLE {tableName} ADD COLUMN {tempColumnName} {newDataType}";
                    cmd.ExecuteNonQuery();
                }

                // 2. 将旧列数据迁移到临时列
                using (var cmd = new SQLiteCommand(connection))
                {
                    cmd.Transaction = transaction;
                    cmd.CommandText = $"UPDATE {tableName} SET {tempColumnName} = {columnName}";
                    cmd.ExecuteNonQuery();
                }

                // 3. 删除旧列
                using (var cmd = new SQLiteCommand(connection))
                {
                    cmd.Transaction = transaction;
                    cmd.CommandText = $"ALTER TABLE {tableName} DROP COLUMN {columnName}";
                    cmd.ExecuteNonQuery();
                }

                // 4. 将临时列重命名为原列名
                using (var cmd = new SQLiteCommand(connection))
                {
                    cmd.Transaction = transaction;
                    cmd.CommandText = $"ALTER TABLE {tableName} RENAME COLUMN {tempColumnName} TO {columnName}";
                    cmd.ExecuteNonQuery();
                }

                // 提交事务
                transaction.Commit();
                Console.WriteLine($"成功将表 {tableName} 中的 {columnName} 列数据类型修改为 {newDataType}");
                return true;
            }
            catch (Exception ex)
            {
                // 发生错误时回滚事务
                transaction.Rollback();
                Console.WriteLine($"修改失败: {ex.Message}");
                throw;
            }
        }
    }
}

方法二
SQLite不能直接修改  表  里面 字段(列)的类型   修改字段类型的方法如下

    1、将表名改为临时表
ALTER TABLE Student RENAME TO _Student_old_20180504;

    2、创建新表
CREATE TABLE Student (Id  INTEGER PRIMARY KEY AUTOINCREMENT, Name  Text);

    3、导入数据
INSERT INTO Student (Id, Name) SELECT Id, Title FROM _Student_old_20180504;
如果列是一一对就  可以insert into Student select * from _Student_old_20180504;
从一个表把数据导入另外一个表是根据列的索引顺序,而不是根据列名

    4、删除旧表
DROP TABLE _Student_old_20180504;


创建 修改表的整个sql语句的方法

/// <summary>
/// 创建 修改表的整个sql语句
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="newTableSql">创建新表的sql语句,注意表名要和 tableName 一样</param>
/// <returns>修改表的整个sql语句</returns>
public string BuildHBCSQL(string tableName,string newTableSql)
{
    StringBuilder ha2 = new StringBuilder();
    string sqlstr = $"select count(*)  from sqlite_master where name = '{tableName}'";
    int i1 = Convert.ToInt32(tool.DAL.SQLiteHelper.ExecuteScalar(sqlstr));
    if (i1 < 1)//要修改的表是否存在
    {
        //不存在,直接创建该表
        ha2.Append(newTableSql);
    }
    else
    {
        string alterTableSQL = $" ALTER TABLE '{tableName}' RENAME TO '_{tableName}_old_20240612';";
        if (SQLiteHelper.ExecSQL(alterTableSQL))
        {
            ha2.AppendLine(newTableSql);
            ha2.AppendLine($"  INSERT INTO {tableName} (");
            string tempHA2SQL = $"select * from _{tableName}_old_20240612 where 1=2";
            DataSet ds = SQLiteHelper.ExecuteQuery(tempHA2SQL, null);

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Columns.Count > 0)
            {
                string tempColumnName = string.Empty;
                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                {
                    tempColumnName = ds.Tables[0].Columns[i].ColumnName;
                    ha2.Append(tempColumnName);
                    if (i != ds.Tables[0].Columns.Count - 1)
                    {
                        ha2.AppendLine(",");
                    }
                }
                ha2.AppendLine(")");
                ha2.AppendLine("  SELECT ");
                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                {
                    tempColumnName = ds.Tables[0].Columns[i].ColumnName;
                    ha2.Append(tempColumnName);
                    if (i != ds.Tables[0].Columns.Count - 1)
                    {
                        ha2.AppendLine(",");
                    }
                }
                ha2.AppendLine($" from _{tableName}_old_20240612 ;");
                ha2.AppendLine($"DROP TABLE _{tableName}_old_20240612 ;");
            }
        }

    }
    return ha2.ToString();
}
/// <summary>
/// 创建新表的Sql语句
/// </summary>
private string CreateErrorDetailSql = @"CREATE TABLE ErrorDetail ( 
                            id       INTEGER PRIMARY KEY,
                            ParentId INT,
                            PHASE    TEXT,
                            U        TEXT,
                            I        TEXT,
                            J        TEXT,
                            INPUT    TEXT,
                            ERROR    TEXT,
                            ERROR2   TEXT
                        );";

本文来自 www.Luofenming.com

视频教程,进入B站可看高清视频教程