关于c#:无法启动连接


Connection can′t be started

我有一个无法修复的错误。

1
2
3
4
5
6
 SqlConnection cn = new SqlConnection(@"Data Source=
                 (LocalDB)\\v11.0;AttachDbFilename=
                  C:\\Users\\gpsi1_000\\Desktop\\Pap
                  Fábio\\db\\clientes.mdf;Integrated Security=True;
                  Connect Timeout=30"
);
 SqlCommand cmd = new SqlCommand();

这是我连接数据库的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if (txtnovocp.Text !="" & txtnovamora.Text !=""
               & txtnovaloca.Text !="" & txtnovoconce.Text !="")
 {
    cn.Open();
    cmd.CommandText ="INSERT INTO Postal  
                     (Codigo_Postal,Morada,Localidade,Concelho)
                     VALUES('"
+ txtnovocp.Text +"','" +
                     txtnovamora.Text +"', '" + txtnovaloca.Text
                      +"' , '" + txtnovoconce.Text +"')";
    cmd.ExecuteNonQuery();
    cmd.Clone();
    MessageBox.Show("Código-Postal Inserido");
    cn.Close();
    txtnovocp.Text ="";
    txtnovaloca.Text ="";
    txtnovamora.Text ="";
    txtnovoconce.Text ="";
  }

这是我要在Postal

中插入的代码

但是当我单击按钮保存值时,显示一个错误:

1
2
3
4
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.Data.dll
Additional information: ExecuteNonQuery:
A propriedade Connection n?o foi inicializada.


尝试:

1
2
3
4
5
6
using (var connection =  new SqlConnection...)
{
    connection.Open();
    var cmd = connection.CreateCommand();
    ...
}

英语错误消息为:

Additional information: ExecuteNonQuery: The Connection property is
not initialized.

我觉得这很有意义,不是吗?您必须初始化连接并将其分配给命令。

1
2
3
SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\gpsi1_000\\Desktop\\Pap Fábio\\db\\clientes.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;  // <-----

如果这是该类的成员,则不能将连接分配给命令内联。通常,您使用该类的构造函数。

1
2
3
4
5
6
7
8
9
SqlConnection cn = null;
SqlCommand cmd = null;

public ClassName()
{
    cn = new SqlConnection(@"Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\gpsi1_000\\Desktop\\Pap Fábio\\db\\clientes.mdf;Integrated Security=True;Connect Timeout=30");
    cmd = new SqlCommand();
    cmd.Connection = cn;
}