C# SQL Server Bağlantısı
Windows Form Uygulamalarında MS SQL Server Bağlantı Yönetimi Yapan Bir Sınıf Örneği;
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 |
using System.Data.SqlClient; using System.Windows.Forms; namespace Sql { class DbManager { private SqlConnection conn; public SqlConnection Conn { get { if (this.conn == null) { conn = new SqlConnection(); // Eğer Boşsa Bağlantı Nesnesini Oluştur conn.ConnectionString = GetConnectionString(); } if (conn.State != System.Data.ConnectionState.Open) { try { conn.Open(); //Bağlantı Açık Değil is Aç } catch (SqlException ex) { MessageBox.Show(ex.Message, "Hata : Sql Bağlantısı Açılamadı"); } } return conn; } } public void BaglantiyiKapat() { if (Conn.State == System.Data.ConnectionState.Open) { try { Conn.Close(); //Eğer Bağlantı Açık ise Kapat } catch (SqlException ex) { MessageBox.Show(ex.Message, "Hata : SQL Bağlantısı Kapatılamadı"); } } } string GetConnectionString() //SQL Connection String Oluşturucu { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = "SQLSERVER"; //SQL Sunucu Adı builder.UserID = "sa"; //Kullanıcı Adı builder.Password = "1234"; //Kullanıcı Şifresi builder.InitialCatalog = "DATABASE"; //Veri Tabanı return builder.ToString(); } } } |
Son Yorumlar