using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient;//引用名空间 namespace _14._9_Connection_连接_关闭数据库 { class Program { static void Main(string[] args) { //数据库的连接分为两种方式 //SQL Server数据库 //windows身份验证登陆并打开数据库 //string constr = "Server=.;integrated security=SSPI;Initial Catalog=csharpzxw"; //SQL验证方式登录 string constr = "Server=.;user=sa;pwd=sa;database=csharpzxw"; SqlConnection mysqlCon = new SqlConnection(constr); //mysqlCon.Open();//打开数据库 //Console.WriteLine("数据库成功打开"); //mysqlCon.Close();//关闭数据库 //Console.WriteLine("数据库成功关闭"); using (mysqlCon)//通过using语句实现数据库关闭 { mysqlCon.Open();//打开数据库 if (mysqlCon.State == System.Data.ConnectionState.Open) Console.WriteLine("数据库成功打开"); else Console.WriteLine("数据库未打开"); mysqlCon.Close();//关闭数据库 if (mysqlCon.State == System.Data.ConnectionState.Closed) { Console.WriteLine("数据库成功关闭"); } else { Console.WriteLine("数据库未关闭"); } } try//通过try...catch...finally语句关闭数据库 { mysqlCon.Open(); if (mysqlCon.State == System.Data.ConnectionState.Open) Console.WriteLine("数据库成功打开"); else Console.WriteLine("数据库未打开"); } catch { } finally { mysqlCon.Close(); if (mysqlCon.State == System.Data.ConnectionState.Closed) { Console.WriteLine("数据库成功关闭"); } else { Console.WriteLine("数据库未关闭"); } } try//try...catch...finally和using结合使用 { using (mysqlCon) { mysqlCon.Open(); if (mysqlCon.State == System.Data.ConnectionState.Open) Console.WriteLine("数据库成功打开"); else Console.WriteLine("数据库未打开"); } } catch { } finally { if (mysqlCon.State == System.Data.ConnectionState.Closed) { Console.WriteLine("数据库成功关闭"); } else { Console.WriteLine("数据库未关闭"); } //mysqlCon.Close(); //Console.WriteLine("数据库成功关闭"); } Console.ReadKey(); } } }
伙计,这个格式太乱了,没法看啊……