Asenkron ulanish. Asenkron ulanishni yaratish uchun siz asenkron OpenAsync () usulidan foydalanishingiz kerak:
class Program { static void Main(string[] args) { ConnectWithDB().GetAwaiter(); } private static async Task ConnectWithDB() { string connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=usersdb;Integrated Security=True"; using (SqlConnection connection = new SqlConnection(connectionString)) { await connection.OpenAsync(); Console.WriteLine("Подключение открыто"); } Console.WriteLine("Подключение закрыто..."); } } Ulanish to'g'risida ma'lumot olish. SqlConnection ob'ekti ulanish ma'lumotlarini olishga imkon beradigan bir qator xususiyatlarga ega:
string connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=usersdb;Integrated Security=True"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); Console.WriteLine("Подключение открыто"); // Вывод информации о подключении Console.WriteLine("Свойства подключения:"); Console.WriteLine("\tСтрока подключения: {0}", connection.ConnectionString); Console.WriteLine("\tБаза данных: {0}", connection.Database); Console.WriteLine("\tСервер: {0}", connection.DataSource); Console.WriteLine("\tВерсия сервера: {0}", connection.ServerVersion); Console.WriteLine("\tСостояние: {0}", connection.State); Console.WriteLine("\tWorkstationld: {0}", connection.WorkstationId); } Console.WriteLine("Подключение закрыто..."); Mening holatimda konsol chiqishi:
Mumkin bo'lgan xatolar va ularni hal qilish.
Ma'lumotlar bazasiga ulanishda siz bir qator xatolarga duch kelishingiz mumkin, eng keng tarqalganlaridan biri quyidagilar:
Unhandled Exception: System.ArgumentException: Keyword not supported... Ushbu xato ulanish simlari parametrlarining noto'g'ri spetsifikatsiyasi tufayli yuzaga keldi va biz ulanish simini qanday aniqlashimiz muhim emas - kodda yoki konfiguratsiya faylida. Xato xabari, qoida tariqasida, qaysi parametr noto'g'ri ko'rsatilganligini aytadi, bu holda uni tuzatish kerak.
Yana bir keng tarqalgan xato, bu ma'lumotlar bazasi mavjud emas yoki hech bo'lmaganda joriy foydalanuvchi uchun shunga o'xshash ma'lumotlar bazasi yo'q:
Cannot open database "MB ni nomlanishi" requested by the login. The login failed. Login failed for user 'foydalanuvchi_nomlanishi' Bunday holda, serverda xuddi shu nomdagi ma'lumotlar bazasi mavjudligiga ishonch hosil qilishingiz kerak va agar mavjud bo'lsa, ushbu foydalanuvchiga ushbu ma'lumotlar bazasiga kirish huquqi borligini tekshiring.
Va yana bir keng tarqalgan xato:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible... Bunday holda, qoida tariqasida, SQL Server ishlamaydi. Va uni xizmat paneli orqali boshlash yoki qayta boshlash kerak. Bundan tashqari, ulanish nomida noto'g'ri server nomi mavjud yoki MS SQL Server umuman o'rnatilmagan bo'lishi mumkin.