如何更改数据库的大小

时间:2010-03-20 19:38:53

标签: c#

我知道如何更改SQL上的大小数据库(在SQL Server 2005 Express Edition中)

ALTER DATABASE Accounting
MODIFY FILE
(NAME = 'Accounting',
SIZE = 25)

如何更改使用C#的大小数据库?

2 个答案:

答案 0 :(得分:3)

通过ExecuteNonQuery命令提交DDL:

mySqlCommand = mySqlConnection.CreateCommand();

mySqlCommand.CommandText =
  "ALTER DATABASE Accounting MODIFY FILE (NAME = 'Accounting', SIZE = 25) ";

mySqlConnection.Open();
int result = mySqlCommand.ExecuteNonQuery();
mySqlConnection.Close();

此处可以找到类似的示例(显示与快照隔离相关的问题,但理念基本相同):

http://msdn.microsoft.com/en-us/library/tcbchxcb.aspx

答案 1 :(得分:0)

以下示例将为您提供更好的概述。定义参数后,您可以传递一些不必要的东西,这些东西必须是静态的。使用using将确保正确处理/关闭所有内容(并在必要时重新使用)。

     public const string sqlDataConnectionDetails = "Data Source=YOUR-SERVER;Initial Catalog=YourDatabaseName;Persist Security Info=True;User ID=YourUserName;Password=YourPassword";

     public static void ChangeDatabaseSize(int databaseSize) {
        const string preparedCommand = @"
                        ALTER DATABASE Accounting
                        MODIFY FILE
                        (NAME = 'Accounting', SIZE = @size)
                        ";
        using (var varConnection = SqlConnectOneTime(sqlDataConnectionDetails))
        using (SqlCommand sqlWrite = new SqlCommand(preparedCommand, varConnection)) {
            sqlWrite.Parameters.AddWithValue("@size", databaseSize);
            sqlWrite.ExecuteNonQuery();
        }
    }

这是一种支持方法,可以在每次要向数据库写入/读取内容时轻松建立连接。

    public static SqlConnection SqlConnectOneTime(string varSqlConnectionDetails) {
        SqlConnection sqlConnection = new SqlConnection(varSqlConnectionDetails);
        try {
            sqlConnection.Open();
        } catch {
            DialogResult result = MessageBox.Show(new Form {
                                                               TopMost = true
                                                           }, "No connection to database. Do you want to retry?", "No connection (000001)", MessageBoxButtons.YesNo, MessageBoxIcon.Stop);
            if (result == DialogResult.No) {
                if (Application.MessageLoop) {
                    // Use this since we are a WinForms app
                    Application.Exit();
                } else {
                    // Use this since we are a console app
                    Environment.Exit(1);
                }
            } else {
                sqlConnection = SqlConnectOneTime(varSqlConnectionDetails);
            }
        }
        return sqlConnection;
    }