我正在尝试连接到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;
}
}
答案 0 :(得分:3)
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;
}
}