[英]Can I verify a mysql schema without doing it line by line
I have a program that uses a local database. 我有一个使用本地数据库的程序。 Users have different versions of the program, which in turn has a command to update their database. 用户具有该程序的不同版本,该程序又具有更新其数据库的命令。 So now I have this huge block of code that looks like: 因此,现在我有了这段巨大的代码块,如下所示:
try
{
using (var cmd = new MySqlCommand("ALTER TABLE `SomeTable` ADD COLUMN `SomeColumn` double NULL ;", con))
{
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
I have hundreds of these that add or drop columns, add tables, create indexes, etc. Is there a more efficient way of doing this, like verifying the entire schema at once, or am I stuck maintaining it? 我有成百上千个这样的对象,它们可以添加或删除列,添加表,创建索引等。是否有更有效的方法来做到这一点,例如一次验证整个架构,还是坚持维护呢? I do intend to change it to an array of strings and just run all the strings in the array, but I didn't know if there was a better way to do this. 我确实打算将其更改为字符串数组,然后仅运行该数组中的所有字符串,但是我不知道是否有更好的方法来执行此操作。
You can query the whole schema in the database at once from the database information_schema
. 您可以从数据库information_schema
一次查询数据库中的整个架构。 So you can verify all columns settings with one query. 因此,您可以通过一个查询来验证所有列设置。 You can parse the result and check which updates are needed. 您可以解析结果并检查需要哪些更新。 (The database information_schema
is specific for MySQL): (数据库information_schema
是特定于MySQL的):
SELECT * FROM `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA = "<your_database>"
For the future keep it easy an create a table like dbversion
within the database. 为了将来dbversion
,请在数据库中创建一个类似于dbversion
的表。 This table is holding the database version as an arbitrary string (eg "1.1.2") and the date, when the update was performed on this database. 该表将数据库版本保存为任意字符串(例如“ 1.1.2”)和在此数据库上执行更新的日期。 So you can query what schema version the database is and do your update if necessary. 因此,您可以查询数据库的架构版本,并在必要时进行更新。
Do the update of this database only if all updates where performed successfully. 仅当所有更新都成功执行时,才执行此数据库的更新。 Another way is to insert a dataset before the update as semaphore that the update is in progress. 另一种方法是在更新之前插入数据集,作为正在进行更新的信号。
Eg version = "1.1.3 updating" and after the update was successful delete this added row and add version = "1.1.3". 例如,版本=“ 1.1.3更新”,并在更新成功后删除此添加的行,并添加版本=“ 1.1.3”。
CREATE TABLE `dbversion` (
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`version` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `dbversion`
ADD PRIMARY KEY (`date`,`version`),
ADD KEY `date` (`date`);
Get the newest entry with in dbversion
: 使用dbversion
获取最新条目:
SELECT * FROM `dbversion` ORDER BY `date` DESC LIMIT 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.