测试 SQL 连接字符串可用性的最有效方法 [英] Most efficient way to test SQL connection string availibility
问题描述
我有这段代码,我试图让它测试 SQL 字符串连接,但我不知道如何处理带有 connection.Open = true
的部分,你能帮我解决这个问题吗?非常感谢您抽出宝贵时间.
I have this code down which I tried to make it Test SQL string connectivity, but I dont know how to handle the part with connection.Open = true
would you please help me to solve this out? Thank you so much for your time.
private void button1_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection connection = new SqlConnection("Data Source='" + textBox1.Text + "';Initial Catalog='" + textBox2.Text + "';User ID='" + textBox3.Text + "';Password='" + textBox4.Text + "'"))
{
try
{
connection.Open();
if (connection.Open == true) // if connection.Open was successful
{
MessageBox.Show("You have been successfully connected to the database!");
}
else
{
MessageBox.Show("Connection failed.");
}
}
catch (SqlException) { }
}
}
catch (Exception ex)
{
MessageBox.Show("Chyba v přihlášení: " + ex);
}
finally
{
}
}
它说:不能分配'打开',因为它是一个'方法组'"我知道这段代码可能非常糟糕,但我需要以某种方式处理这个问题,并且不知道什么是正确的方法.谢谢.
It says: "Cannot asign 'open' because it is a 'methoud group' " I know that this code might be totaly bad, but I need to handle this somehow and have no idea what is the right way. Thank you.
这对于未打开的连接实际上不起作用:
This is what is not actually working for not-opened connection:
using (SqlConnection connection = new SqlConnection("Data Source='" + textBox1.Text + "';Initial Catalog='" + textBox2.Text + "';User ID='" + textBox3.Text + "';Password='" + textBox4.Text + "'"))
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
MessageBox.Show("Spojení s databázi problěhlo úspěšně.");
}
connection.Close();
if (connection.State == ConnectionState.Closed)
{
MessageBox.Show("Spojení selhalo");
}
}
推荐答案
您正在使用 connection.Open = true
,就好像它是一个属性一样.
You're using connection.Open = true
as if it were a property.
这是一个方法:connection.Open()
使用 ConnectionState 枚举来确定连接是否打开,例如:
Use the ConnectionState enum to determine if the connection is open or not, eg:
connection.State == ConnectionState.Open
这篇关于测试 SQL 连接字符串可用性的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!