定义 数据库连接
string connStr = “Data Source=.;Initial Catalog=MySchool;User ID=A129;Pwd=000000”;
创建连接对象
SqlConnection conn = new SqlConnection(connStr);
开启连接
conn.Open();
关闭连接
conn.Close();
//连接数据库
string connStr = "Data Source=.;User ID=A129;Password=000000;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
//创建连接对象
SqlConnection conn = new SqlConnection(connStr);
try
{
//打开连接
conn.Open();
Console.WriteLine("数据库连接成功");
//操作数据
//关闭数据
}
catch (Exception ex)
{
Console.WriteLine("数据库连接失败" + ex);
}
finally{
conn.Close();
Console.WriteLine("数据关闭");
}