无法启动连接

时间:2015-05-22 15:33:27

标签: c#

我有一个我无法解决的错误。

 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();

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

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中插入的代码

但是当我点击按钮保存值时显示错误:

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

2 个答案:

答案 0 :(得分:1)

在英语中,错误信息是:

  

其他信息:ExecuteNonQuery:Connection属性是   没有初始化。

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

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;  // <-----

如果这是该类的成员,则无法将该连接分配给内联命令。通常你使用类的结构函数。

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;
}

答案 1 :(得分:1)

尝试:

using (var connection =  new SqlConnection...)
{
    connection.Open();
    var cmd = connection.CreateCommand();
    ...
}