Merhaba, bu yazıda sizlere C# ile MSSQL Database Oluşturma hakkında bilgi vereceğim.
Database Oluşturma Nerede İşimize Yarar ?
Bildiğiniz gibi zaten MSSQL ile database rahatlıkla oluşturulabiliyor. Sürekli aynı işlemleri yapmak istemiyorsanız ve bunu sistematik hale getirmek istiyorsanız. Bir program yapmanız gerekmektedir. Özellikle uzak bir sunucuda ticari amaçlı bir yazılımınız varsa ve sürekli olarak database oluşturmak zorunda kalıyorsanız gerekli olan bilgiler burada bulunmaktadır.
Şimdi yavaş yavaş projemizin nasıl yapılacağına geçmek istiyorum.İlk önce gerekli DLL’leri sistemimize eklememiz gerekiyor. DLL eklemeyi daha önceki konularda gösterdiğim için burada göstermeyeceğim ve direk olarak ismini yazacağım. Projenin kodlarını parça parça anlatarak gideceğim ama en altta tamamını paylaşacağım.
1 | System.configuration |
Daha sonra Using Namespace’sine aşağıdaki kodu ekliyoruz.
1 2 3 | using System.Data; using System.Data.SqlClient; using System.IO; |
Burası programının kontrol bölümü database adının boş geçilmemesi, kullanıcı adının boş geçilmemesi, şifrenin boş geçilmemesi, mdf dosyasının seçilmesi ve ldf dosyasının seçilmesini kontrol ediyorum. Bu kod blogunun arasına diğer işlemleri yapacağız. Başı ve sonu birleştirdim çünkü ayrı ayrı gösterirsem karmaşıklık olabilir diye düşündüm.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | errorProvider1.Clear(); if (txtDatabase.Text.Length > 0) { if (txtKullaniciAdi.Text.Length > 0) { if (txtSifre.Text.Length > 0) { if (!string.IsNullOrEmpty(openMDF.FileName)) { if (!string.IsNullOrEmpty(openLDF.FileName)) { } else { errorProvider1.SetError(SqlImport2, "Lütfen LDF dosyası seçiniz."); } } else { errorProvider1.SetError(SqlImport, "Lütfen MDF dosyası seçiniz."); } } else { errorProvider1.SetError(txtSifre, "Lütfen şifre giriniz."); } } else { errorProvider1.SetError(txtKullaniciAdi, "Lütfen kullanıcı adı giriniz."); } } else { errorProvider1.SetError(txtDatabase, "Lütfen database adı giriniz."); } |
Burada bizim verdiğimiz database ismi daha önce kullanılmış mı onu kontrol ediyoruz. Eğer yoksa işlemimiz devam edecek yoksa bize mesaj olarak bildirecek.
1 2 3 4 5 6 | string query = "select name from sys.databases where name='" + txtDatabase.Text + "'"; SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=master;Integrated Security=True"); SqlDataAdapter da = new SqlDataAdapter(query, con); DataTable dt = new DataTable(); con.Open(); da.Fill(dt); |
Burada database dosyalarımızı taşıyoruz.
1 2 3 4 | File.Move(openMDF.FileName, Path.GetDirectoryName(openMDF.FileName) + "\\" + txtDatabase.Text + ".mdf"); openMDF.FileName = Path.GetDirectoryName(openMDF.FileName) + "\\" + txtDatabase.Text + ".mdf"; File.Move(openLDF.FileName, Path.GetDirectoryName(openLDF.FileName) + "\\" + txtDatabase.Text + "_log.ldf"); openLDF.FileName = Path.GetDirectoryName(openLDF.FileName) + "\\" + txtDatabase.Text + "_log.ldf"; |
Eğer MSSQL Data yolunda databasenize verdiğiniz isimde bir dosya varsa bize uyarı verecektir. Eğer yoksa dosyaları dosya yoluna kopyalayacaktır. Ben burada kendim elle verdim dosya yollarını sizde kendinize göre dosya yollarını düzenleyebilirsiniz.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | if (File.Exists("C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openMDF.SafeFileName)) { MessageBox.Show("Belirtilen klasörde " + openMDF.SafeFileName + " isimli dosya zaten mevcut...", "Uyarı..!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { File.Copy(openMDF.FileName, "C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openMDF.SafeFileName); } if (File.Exists("C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openLDF.SafeFileName)) { MessageBox.Show("Belirtilen klasörde " + openLDF.SafeFileName + " isimli dosya zaten mevcut...", "Uyarı..!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { File.Copy(openLDF.FileName, "C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openLDF.SafeFileName); } openMDF.FileName = "C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openMDF.SafeFileName; openLDF.FileName = "C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openLDF.SafeFileName; |
Artık database oluşturmaya geldik. Aşağıdaki kodla database ATTACH ediyoruz.
1 2 3 4 | query = "CREATE DATABASE [" + txtDatabase.Text + "] ON ( FILENAME = N'" + openMDF.FileName + "' ), ( FILENAME = N'" + openLDF.FileName + "' ) FOR ATTACH; ALTER DATABASE [" + txtDatabase.Text + "] SET READ_WRITE;"; SqlCommand cmd = new SqlCommand(query); cmd.Connection = con; md.ExecuteNonQuery(); |
Burada vermiş olduğumuz kullanıcı adı ve şifreye göre MSSQL de kullanıcı oluşturuyoruz.
1 2 3 4 5 6 7 | con.Close(); con.Open(); query = "CREATE LOGIN " + txtKullaniciAdi.Text + " WITH PASSWORD ='" + txtSifre.Text + "'"; SqlCommand command = new SqlCommand(query); command.Connection = con; command.ExecuteNonQuery(); con.Close(); |
Burada ise oluşturmuş olduğumuz kullancının hiçbir database görmemesini sağlıyoruz. Neden olarak bir kullanıcı sadece oluşturulmuş olan database görmesi gerekiyor. Onuda aşağıdaki bölümde yapacağız. Buda bize güvenliği sağlamış olacaktır.
1 2 3 4 5 6 | con.Open(); query = "DENY View any database TO " + txtKullaniciAdi.Text; command = new SqlCommand(query); command.Connection = con; command.ExecuteNonQuery(); con.Close(); |
Burada ise oluşturmuş olduğumuz kullanıcıya ATTACH ettiğimiz database yetkisini veriyoruz.
1 2 3 4 5 6 7 | con.Open(); query = "USE [" + txtDatabase.Text + "] EXEC sp_changedbowner " + txtKullaniciAdi.Text; command = new SqlCommand(query); command.Connection = con; command.ExecuteNonQuery(); con.Close(); MessageBox.Show("Database oluşturuldu.", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); |
Projede ben errorprovider ve 2 adette openfiledialog kullandım ekstra olarak ben biraz daha profesyonel bir şey olsun diye özendim anlamadığınız bir nokta olursa mail ve yorum atabilirsiniz. Şuan bu sistemi ben başarılı bir şekilde kullanmaktayım.
Kodun Tamamı :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | errorProvider1.Clear(); if (txtDatabase.Text.Length > 0) { if (txtKullaniciAdi.Text.Length > 0) { if (txtSifre.Text.Length > 0) { if (!string.IsNullOrEmpty(openMDF.FileName)) { if (!string.IsNullOrEmpty(openLDF.FileName)) { string query = "select name from sys.databases where name='" + txtDatabase.Text + "'"; SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=master;Integrated Security=True"); SqlDataAdapter da = new SqlDataAdapter(query, con); DataTable dt = new DataTable(); con.Open(); da.Fill(dt); if (dt.Rows.Count == 0) { File.Move(openMDF.FileName, Path.GetDirectoryName(openMDF.FileName) + "\\" + txtDatabase.Text + ".mdf"); openMDF.FileName = Path.GetDirectoryName(openMDF.FileName) + "\\" + txtDatabase.Text + ".mdf"; File.Move(openLDF.FileName, Path.GetDirectoryName(openLDF.FileName) + "\\" + txtDatabase.Text + "_log.ldf"); openLDF.FileName = Path.GetDirectoryName(openLDF.FileName) + "\\" + txtDatabase.Text + "_log.ldf"; if (File.Exists("C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openMDF.SafeFileName)) { MessageBox.Show("Belirtilen klasörde " + openMDF.SafeFileName + " isimli dosya zaten mevcut...", "Uyarı..!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { File.Copy(openMDF.FileName, "C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openMDF.SafeFileName); } if (File.Exists("C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openLDF.SafeFileName)) { MessageBox.Show("Belirtilen klasörde " + openLDF.SafeFileName + " isimli dosya zaten mevcut...", "Uyarı..!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { File.Copy(openLDF.FileName, "C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openLDF.SafeFileName); } openMDF.FileName = "C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openMDF.SafeFileName; openLDF.FileName = "C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\" + openLDF.SafeFileName; query = "CREATE DATABASE [" + txtDatabase.Text + "] ON ( FILENAME = N'" + openMDF.FileName + "' ), ( FILENAME = N'" + openLDF.FileName + "' ) FOR ATTACH; ALTER DATABASE [" + txtDatabase.Text + "] SET READ_WRITE;"; SqlCommand cmd = new SqlCommand(query); cmd.Connection = con; cmd.ExecuteNonQuery(); con.Close(); con.Open(); query = "CREATE LOGIN " + txtKullaniciAdi.Text + " WITH PASSWORD ='" + txtSifre.Text + "'"; SqlCommand command = new SqlCommand(query); command.Connection = con; command.ExecuteNonQuery(); con.Close(); con.Open(); query = "DENY View any database TO " + txtKullaniciAdi.Text; command = new SqlCommand(query); command.Connection = con; command.ExecuteNonQuery(); con.Close(); con.Open(); query = "USE [" + txtDatabase.Text + "] EXEC sp_changedbowner " + txtKullaniciAdi.Text; command = new SqlCommand(query); command.Connection = con; command.ExecuteNonQuery(); con.Close(); MessageBox.Show("Database oluşturuldu.", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Bu database adı bulunmaktadır.", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { errorProvider1.SetError(SqlImport2, "Lütfen LDF dosyası seçiniz."); } } else { errorProvider1.SetError(SqlImport, "Lütfen MDF dosyası seçiniz."); } } else { errorProvider1.SetError(txtSifre, "Lütfen şifre giriniz."); } } else { errorProvider1.SetError(txtKullaniciAdi, "Lütfen kullanıcı adı giriniz."); } } else { errorProvider1.SetError(txtDatabase, "Lütfen database adı giriniz."); } |
Ekran Görüntüsü:
Soru ve görüşleriniz için [email protected] adresine mail atabilirsiniz.