本文介绍了类型的未处理的异常'System.InvalidOperationException'出现在system.data.dll当我试图将数据插入文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建从Visual Studio中我的数据库的连接。

i am creating a connection to my database from from visual studio.

这是我的code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;


public partial class CM : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("server =KIRITI; database =msdb; Integrated Security=True");

protected void Button1_Click(object sender, EventArgs e)
{
    con.Open();
    String NotesMaker = TextBox1.Text;
    SqlCommand cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values('"+NotesMaker+"',con)");
    cmd.ExecuteNonQuery();
    cmd.CommandText = "Select@@Identity";
    con.Close();
}
}

我得到command.Executenonquery()的错误:类型的异常'System.InvalidOperationException'出现在system.data.dll但在用户code没有处理

I get an error at command.Executenonquery(): An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code

更多信息:的ExecuteNonQuery:Connection属性尚未初始化

Additional information: ExecuteNonQuery: Connection property has not been initialized.

请帮助!我从两天受阻!

Please help!! I'm blocked from two days!!

推荐答案

这就是连接首先,我所看到的字符串连接导致要查询的一部分

Thats the first place where I have seen string concatenation causing conn to be part of query.

您错位字符串引号,你的说法应该是:

You misplaced string quotes, your statement should be:

SqlCommand cmd =
  new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values('" + NotesMaker + "'",con);

在你目前的code,你通过字符串INSERT INTO NOTESMAKER(NOTESMAKER)VALUES('+ NotesMaker +',CON),因此,连接属性没有初始化,因此例外。

In your current code, you are passing string "Insert into NOTESMAKER(NOTESMAKER) Values('"+NotesMaker+"',con)", hence the connection property is not initialized and hence the exception.

您不应该使用字符串连接创建查询,而是使用参数。这将节省您从。这样的:

You should never use string concatenation for creating queries, instead use Parameters. This will save you from SQL Injection. Like:

using(SqlConnection con = new SqlConnection("connectionstring"))
using(SqlCommand cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(@NotesMaker)",con))
{
    cmd.Parameters.AddWithValue("@NotesMaker", NotesMaker);
    con.Open();
    cmd.ExecuteNonQuery();
}

这篇关于类型的未处理的异常'System.InvalidOperationException'出现在system.data.dll当我试图将数据插入文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:26