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. |
- 可能您没有在任何地方将cn传递给cmd?以其构造函数为例? -另外,您还需要对其进行参数化,因为它容易受到SQL注入的攻击。
-
如果我在所有行中都输入cn会显示错误
-
SqlCommand需要知道应该使用什么连接来访问数据库。您需要设置命令的Connection属性,或者更好地使用适当的构造函数
-
也许您可以花一点精力看一下MSDN的示例? msdn.microsoft.com/zh-CN/library/
-
这是一个基本示例(通过使用slqcommand可以轻松找到)dotnetperls.com/sqlconnection
-
ExecuteNonQuery的可能重复项:Connection属性尚未初始化。
尝试:
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 ;
} |
- 错误\\ t2 \\ t无效的令牌;在类,结构或接口成员声明中
-
错误\\ t1 \\ t无效的令牌=在类,结构或接口成员声明中
-
还有CreateCommand,因此在这种情况下SqlCommand cmd = cn.CreateCommand()无需分配连接。
-
@BrunoGonalves:如果您的类中的字段使用构造函数,则显示一个示例。