![](/img/trans.png)
[英]How to open a connection to a SQL Server database that is already in use in c#?
[英]How to check successful connection to a SQL Server database in C#?
我正在嘗試使用C#連接到SQL Server數據庫,並檢查數據庫是否包含具有3列的空表,但是我不知道如何檢查它是否成功。
我的代碼:
protected bool checkDB()
{
string ConnectionString = "Server=[serverName];Database=[databaseName];Trusted_Connection=true";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand com = new SqlCommand("SELECT * FROM tableName", con);
// use the connection here
con.Open();
con.Close();
if (success)
{
return true;
}
else
{
return false;
}
}
protected bool checkDB()
{
var connString = @"Server=myServerName\myInstanceName;Database=myDataBase;Integrated Security=true;";
try
{
using (var con = new SqlConnection(connString))
{
con.Open();
using (var com = new SqlCommand("SELECT * FROM tableName", con))
{
// use your query here...
}
}
return true;
}
catch (Exception)
{
return false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.