连接无法启动

本文关键字:启动 连接 | 更新日期: 2023-09-27 17:50:23

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

 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.

连接无法启动

尝试:

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

英文错误信息为:

附加信息: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;
}