How to change size of database
I know how to change size database on SQL (in SQL Server 200开发者_StackOverflow中文版5 Express Edition)
ALTER DATABASE Accounting
MODIFY FILE
(NAME = 'Accounting',
SIZE = 25)
How to change size database useing C#?
Submit the DDL via an ExecuteNonQuery
command:
mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"ALTER DATABASE Accounting MODIFY FILE (NAME = 'Accounting', SIZE = 25) ";
mySqlConnection.Open();
int result = mySqlCommand.ExecuteNonQuery();
mySqlConnection.Close();
Similar examples can be found here (showing issues related to snapshot isolation, but the ideais basically the same):
http://msdn.microsoft.com/en-us/library/tcbchxcb.aspx
Following example will give you a better overview. Having defined parameters you can pass some stuff that not necessary has to be static. Using using
will make sure everything is disposed/closed properly (and or reused if necessary).
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();
}
}
This is supporting method that makes it easy to establish connection everytime you want to write/read something to database.
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;
}
精彩评论