PDA

View Full Version : سوال: ایجاد Database از طریق سی شارپ



mr.siahatgar
سه شنبه 01 تیر 1395, 12:39 عصر
سلام دوستان
من یه برنامه نوشتم . حالا میخوام یه دکمه طراحی کنم که با زدن ان یه دیتابیس به اسم mout ساخته بشه و در درون ان یه جدول به اسم onemute در sql server 2014 ساخته بشه
یاداوری کنم که میخواهم تمام اینها از طریق سی شارپ انجام بشه با فرض بر این که هیچ دیتابیسی در sql وجود ندارد . من باید چگونه به اس کیو ال متصل بشم و بعد دیتابیس را بسازم
ممنون

دلتنگ اسمان
سه شنبه 01 تیر 1395, 16:08 عصر
سلام
ساخت دیتابیس با کد :

string constr = @"Server=.\SQLExpress;Integrated security=SSPI";
string constr2 = @"Server=.\SQLExpress;Integrated security=SSPI;database=muot";



private void create_Database()
{
con = new SqlConnection();
com = new SqlCommand();

String str;

SqlConnection Connection = new SqlConnection(constr);
Connection.Open();

con.ConnectionString = constr;
try
{

string executable = System.Reflection.Assembly.GetExecutingAssembly(). Location;
string path = (System.IO.Path.GetDirectoryName(executable));

bool exists = CheckDatabaseExists(constr, "mout");

if (!exists)
{
str = "CREATE DATABASE mout ON PRIMARY " +
"(NAME = mout_Data, " +
"FILENAME = '" + Application.StartupPath + "\\mout.mdf', " +
"SIZE = 4MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = mout_Log, " +
"FILENAME = '" + Application.StartupPath + "\\moutLog.ldf', " +
"SIZE = 4MB, " +
"MAXSIZE = 10MB, " +
"FILEGROWTH = 10%)";

ConnectionState state = Connection.State;

SqlCommand myCommand = new SqlCommand(str, con);

con.Open();

myCommand.ExecuteNonQuery();

con.Close();

}

}
catch (System.Exception ex)
{
MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (con.State == ConnectionState.Open)

con.Close();

}
}


ساخت جدول با کد نویسی:

SqlConnection connection;
SqlCommand command;
connection = new SqlConnection(constr2);
connection.Open();//

createtablestr =
"CREATE TABLE useres (username1 NVARCHAR(50) NOT NULL, " +
"password1 NVARCHAR(150)NOT NULL , " +
"PRIMARY KEY(username1,password1 ))";

command = new SqlCommand(createtablestr, connection);
command.ExecuteNonQuery();