ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

前端 未结 14 1861
青春惊慌失措
青春惊慌失措 2020-11-28 08:45

We\'ve recently had the need to add columns to a few of our existing SQLite database tables. This can be done with ALTER TABLE ADD COLUMN. Of course, if the table has alre

14条回答
  •  独厮守ぢ
    2020-11-28 09:35

    I solve it in 2 queries. This is my Unity3D script using System.Data.SQLite.

    IDbCommand command = dbConnection.CreateCommand();
                command.CommandText = @"SELECT count(*) FROM pragma_table_info('Candidat') c WHERE c.name = 'BirthPlace'";
                IDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    try
                    {
                        if (int.TryParse(reader[0].ToString(), out int result))
                        {
                            if (result == 0)
                            {
                                command = dbConnection.CreateCommand();
                                command.CommandText = @"ALTER TABLE Candidat ADD COLUMN BirthPlace VARCHAR";
                                command.ExecuteNonQuery();
                                command.Dispose();
                            }
                        }
                    }
                    catch { throw; }
                }
    

提交回复
热议问题