我有一个Winforms应用程序,必须将数据从SQL迁移到MySQL。部分功能需要通过添加所需的表来准备目标数据库(并在必要时删除现有表)。
我正在寻找最有效的方法来确定表是否已成功创建。 This question's answer建议执行查询如果成功则返回大于0的整数值。理想情况下,我想执行命令并使用返回值而不是运行另一个查询。这可能吗?
我目前的代码:
MySqlConnection myConnection = new MySqlConnection(ConnectionString);
string sql = @" DROP TABLE IF EXISTS `sf_root_items`;
CREATE TABLE `sf_root_items` (
`ID` varchar(255) NOT NULL,
`LoweredName` varchar(255) DEFAULT NULL,
`MenuName` varchar(255) DEFAULT NULL,
`Title` varchar(255) DEFAULT NULL,
`Description` varchar(255) DEFAULT NULL,
`PageType` varchar(255) DEFAULT NULL,
`ExternalUrl` varchar(255) DEFAULT NULL,
PRIMARY KEY(`ID`)
)";
MySqlCommand cmd;
try
{
if (myConnection.State != ConnectionState.Open)
{
myConnection.Close();
myConnection.Open();
}
cmd = myConnection.CreateCommand();
cmd.CommandText = sql;
int output = cmd.ExecuteNonQuery();
// a value greater than 0 means execution was successful
if (output > 0)
{
DBPrepDone = "Table created";
}
else
{
DBPrepDone = "There was an error";
}
myConnection.Close();
}
catch (Exception ex)
{
DBPrepDone = ex.ToString();
}
答案 0 :(得分:1)
以下是Microsoft站点
的ExecuteNonQuery返回值的说明虽然ExecuteNonQuery没有返回任何行,但任何输出参数或 映射到参数的返回值将填充数据。对于 UPDATE,INSERT和DELETE语句,返回值是数字 受命令影响的行数。当表上存在触发器时 在插入或更新时,返回值包括数量 受插入或更新操作影响的行数和 受触发器或触发器影响的行。对于所有其他类型的 语句,返回值为-1。如果发生回滚,则返回 值也是-1。
要使查询有效,您应该添加对现有表的检查,例如
string sql = @" DROP TABLE IF EXISTS `sf_root_items`;
CREATE TABLE `sf_root_items` (
`ID` varchar(255) NOT NULL,
`LoweredName` varchar(255) DEFAULT NULL,
`MenuName` varchar(255) DEFAULT NULL,
`Title` varchar(255) DEFAULT NULL,
`Description` text,
`PageType` varchar(255) DEFAULT NULL,
`ExternalUrl` varchar(255) DEFAULT NULL,
PRIMARY KEY(`ID`)
)";
string sql_check = @" SELECT count(*)
FROM information_schema.TABLES
WHERE (TABLE_NAME = 'sf_root_items')
AND (TABLE_SCHEMA = '" + WP_db.Text +"')";
MySqlCommand cmd;
try
{
if (myConnection.State != ConnectionState.Open)
{
myConnection.Close();
myConnection.Open();
}
cmd = myConnection.CreateCommand();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
//call check if table was created
cmd = myConnection.CreateCommand();
cmd.CommandText = sql_check;
var test = cmd.ExecuteScalar();
int output;
int.TryParse(test.ToString(), out output);
// a value greater than 0 means execution was successful
if (output > 0)
{
DBPrepDone = "Table 'sf_root_items' has been created";
}
else
{
DBPrepDone = "There was an error";
}
myConnection.Close();
}
catch (Exception ex)
{
DBPrepDone = ex.ToString();
}