【发布时间】:2016-02-15 15:50:38
【问题描述】:
我正在尝试连接到 sql server,但出现此错误:
System.InvalidOperationException:ExecuteNonQuery 需要打开和 可用的连接。连接的当前状态为关闭。在 System.Data.SqlClient.SqlCommand.ValidateCommand(字符串方法, 布尔异步)在 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 完成,字符串方法名,布尔型 sendToPipe,Int32 超时, 布尔 asyncWrite) 在 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() 在 FattureServer.Form1.button4_Click(Object sender, EventArgs e)
string dbserver2 = textBox4.Text;
string dbname2 = textBox1.Text;
string dbusername2 = textBox2.Text;
string dbpassword2 = textBox3.Text;
SqlConnection conn2 = new SqlConnection("Data Source=" + dbserver + ";Initial Catalog=" + dbname + ";User ID=" + dbusername + ";Password=" + dbpassword + "");
// SqlCommand cmd2 = new SqlCommand("INSERT INTO Cliente (IdCliente,IdUtente,RagioneSociale,Titolo,Indirizzo,Stato,Provincia,Citta,Comune,Cap,Telefono,Email) VALUES(@idcliente,@username,@password, @email)", conn2);
string query2 = "INSERT INTO Cliente (Titolo,RagioneSociale) VALUES(@Titolo,@RagioneSociale)";
SqlCommand myCommand = new SqlCommand(query2, conn2);
myCommand.Parameters.AddWithValue("@Titolo", titolo);
myCommand.Parameters.AddWithValue("@RagioneSociale", ragionesociale);
myCommand.ExecuteNonQuery();
conn2.Close();
如何解决这个错误?
编辑:
如果我插入 conn2.open() 我有这个错误:
System.Data.SqlClient.SqlException (0x80131904):对象名称“Cliente”无效。在 System.Data.SqlClient.SqlConnection.OnError(SqlException 异常,布尔 breakConnection,Action1 wrapCloseInAction) 在 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException 异常,布尔 breakConnection,Action1 wrapCloseInAction)在 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,布尔 callerHasConnectionLock,布尔 asyncClose)在 System.Data.SqlClient.TdsParser.TryRun System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds( System.Data.SqlClient.SqlCommand.RunExecuteReader 上的 CommandBehavior cmdBehavior、RunBehavior runBehavior、布尔 returnStream、布尔异步、Int32 超时、任务和任务、布尔异步写入、SqlDataReader ds、布尔 describeParameterEncryptionRequest)(CommandBehavior cmdBehavior、RunBehavior runBehavior、布尔 returnStream、字符串方法、TaskCompletionSource1 完成、Int32 超时、Task& 任务、布尔 asyncWrite) 在 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 完成,字符串方法名,布尔 sendToPipe,Int32 超时,布尔 asyncWrite)在 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() 在 FattureServer.Form1.button4_Click(对象发件人,EventArgs e ) 在 C:\Users\riccardo\Desktop\FattureServer\FattureServer\Form1.cs:line 189 ClientConnectionId:02db8bd4-e91a-4b43-9ba9-e1717c9e96de 错误编号:208,State:1,Class:16
【问题讨论】:
-
你忘了做 conn2.Open();在执行命令之前。
-
您是在问如何解决“ExecuteNonQuery 需要一个打开且可用的连接。连接的当前状态为关闭”?真的吗?
-
你在哪里打开你的连接?连接是一次性的。您应该将您的调用封装在“使用”中。
标签: c# visual-studio error-handling