我有一个数据库user.sdf在asp.net中,我想创建的表,我需要检查它首先检查它的存在是不是如果存在则不需要创建的表,否则创建新的表,我如何检查它,请帮助我解决这个问题。
发布于 2011-06-11 22:44:09
您可以查询SQL CE3.5中的架构视图,请看一下here。
下面是一个您可以使用的简单扩展方法。
public static class SqlCeExtentions
{
public static bool TableExists(this SqlCeConnection connection, string tableName)
{
if (tableName == null) throw new ArgumentNullException("tableName");
if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentException("Invalid table name");
if (connection == null) throw new ArgumentNullException("connection");
if (connection.State != ConnectionState.Open)
{
throw new InvalidOperationException("TableExists requires an open and available Connection. The connection's current state is " + connection.State);
}
using (SqlCeCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "SELECT 1 FROM Information_Schema.Tables WHERE TABLE_NAME = @tableName";
command.Parameters.AddWithValue("tableName", tableName);
object result = command.ExecuteScalar();
return result != null;
}
}
}您可以使用上述方法,如下所示
using (SqlCeConnection connection = new SqlCeConnection(@"Data Source=MyDatabase1.sdf"))
{
connection.Open();
if (connection.TableExists("MyTable"))
{
// The table exists
}
else
{
// The table does not exist
}
}发布于 2013-02-24 08:47:58
作为替代方法,您可以查询该表并捕获抛出的异常。如果存在异常,则未找到该表,否则该表存在。
SELECT TOP 1 1 FROM TableName;一个简单的性能测试比对INFORMATION_SCHEMA的查询有更好的结果。尽管我会认为对INFORMATION_SCHEMA的查询更简洁。
https://stackoverflow.com/questions/6316336
复制相似问题