我记下了这段代码,试图将其测试SQL字符串连接,但是我不知道该如何处理该部分,connection.Open = true请您帮我解决一下吗?非常感谢您的参与。
connection.Open = true
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 { } }
它说:“因为它是一个’方法组’,所以不能指定’open’。”我知道这段代码可能很糟糕,但是我需要以某种方式进行处理,并且不知道正确的方法是什么。谢谢你。
这对于未打开的连接实际上不起作用:
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好像它是一个属性。
这是一种方法: connection.Open()
connection.Open()
使用ConnectionState枚举确定连接是否打开,例如:
connection.State == ConnectionState.Open