Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 数据库处理中的空引用异常_C# - Fatal编程技术网

C# 数据库处理中的空引用异常

C# 数据库处理中的空引用异常,c#,C#,在win表单中的c sharp中,我遇到了一个错误,类似于空引用异常 这是我的代码…而且我在数据库表中找不到任何条目 public partial class Form1 : Form { string strCon, strQry; SqlConnection con; SqlCommand cmd; int rowsaffected; public Form1() { InitializeComponent(); }

在win表单中的c sharp中,我遇到了一个错误,类似于空引用异常 这是我的代码…而且我在数据库表中找不到任何条目

public partial class Form1 : Form
{
    string strCon, strQry;
    SqlConnection con;
    SqlCommand cmd;
    int rowsaffected;

    public Form1()
    {
        InitializeComponent();
    }

    box s2 = new box();
    class box
    {
        protected string fname;
        protected string lname;
        public void name(string s1, string s2)
        {
            fname = s1;
            lname = s2;

        }
    }

    void func(string x, string y)
    {
        s2.name(x, y);
    }

    private void btnClick_Click(object sender, EventArgs e)
    {
        string first = txtFname.Text;
        string last = txtLname.Text;
        func(first, last);

        strQry = "Insert Into Practice Values(" + first + "," + last + " )";

        cmd = new SqlCommand(strQry, con);

        cmd.Connection.Open();

        rowsaffected = cmd.ExecuteNonQuery();

        cmd.Connection.Close();

        MessageBox.Show(+rowsaffected + "  row(s) affected"); 
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        strCon = " Data Source = (local); Initial Catalog = Student; User Id= sa; Password=sa;";
        con = new SqlConnection(strCon);
    }


对不起,我没有提到初始化它,你的意思是说con=newsqlconnection(strCon);我已在dat案例中执行dat错误为{“此上下文中不允许使用名称'xyz'。此处只允许使用常量、表达式或变量。不允许使用列名。}

您没有实例化con变量,例如:

SqlConnection con = new SqlConnection(connectionString);

我想发生错误是因为您使用了con,而con未初始化


我没有看到SqlConnection con=newSQLConnection(strCon)

您正在设置连接字符串吗?您似乎正在访问连接对象,但没有告诉它在何处插入数据


cmd.Connection.ConnectionString=“一些字符串”

我认为您不需要
cmd.Connection.Open
cmd.Connection.Close


cmd
将打开并关闭连接,以便执行查询/存储过程。

您实际上正在正确创建连接。发生的事情是,如果您查看连接字符串

strCon=“数据源=(本地);初始目录=学生;用户Id=sa;密码=sa;”

当它尝试连接时,它会这样读:

数据源:“(本地)” 初始目录:“学生” 用户Id=“sa” 密码-“sa”

因此,等号后面的空格将传递给SQL server。你的绳子应该是这样的

strCon=“数据源=(本地);初始目录=学生;用户Id=sa;密码=sa;”


我敢肯定,您永远不会获得到数据库的实际连接,但它会无声地失败。

任何时候,当您在一条有多个调用链接在一起的线路上获得空引用时,如:

    something.somethingElse.somethingElse
把它拆开,检查每一块。例如,在您的情况下,此代码:

    cmd = new SqlCommand(strQry, con);
    SqlConnection sc = cmd.Connection;
    System.Diagnostics.Debug.Assert(sc != null, "You got a null connection from the SqlCommand.");
    sc.Open();

可以演示问题所在。

我打赌您的问题在于连接字符串,并且连接对象为空。以下是生成和测试连接字符串的快速方法:

  • 右键单击windows桌面或windows资源管理器中的文件夹
  • 单击新建->文本文档
  • 将新文件重命名为Test.udl(.udl代表通用数据链接)
  • 使用UDL对话框创建并测试连接,然后单击“确定”
  • 将Test.udl重命名为Test.txt并打开文本文件 文本文件将具有一个有效的连接字符串,您可以在代码中使用该字符串

    另外,为了供您参考,我简化了您的代码。以下内容应更易于调试:

        private const string dbConnection = "USE THE UDL STRING HERE";
    
        private void btnClick_Click(object sender, EventArgs e)
        {
            string first = txtFname.Text;
            string last = txtLname.Text;
            //I think the orig code was missing the single quotes
            string query = string.Format("INSERT INTO Practice ('{0}','{1}')", first, last);
    
            int rowsAffected = 0;
    
            //Using statement will automatically close the connection for you
            //Using a const for connection string ensures .NET Connection Pooling
            using (SqlConnection conn = new SqlConnection(dbConnection))
            {
                //Creates a command associated with the SqlConnection
                SqlCommand cmd = conn.CreateCommand();
    
                //Set your sql statement
                cmd.CommandText = query;
    
                //open the connection
                cmd.Connection.Open();
    
                //Execute the connection
                rowsAffected = cmd.ExecuteNonQuery();
            }
            MessageBox.Show(rowsAffected + " rows Affected");
        }
    

    我认为您没有在代码中创建“SqlConnection con”。您从未在任何地方初始化它,您声明了它,但从未初始化。对不起,我没有提到初始化它,您的意思是说con=newsqlconnection(strCon);我已经在dat中完成了dat,错误是{“在这个上下文中不允许使用名称'xyz'。这里只允许使用常量、表达式或变量。不允许使用列名。}你们为什么把答案作为注释发布?把它作为答案贴出来,这样你就可以得到分数。有人必须说出来。。。“小Bobby Tables”会伤害到你的…看看Form1_Load()-OP正在那里做这件事。@JeffH,这是在这个答案发布后编辑到问题中的。看看对这个问题的评论。@Brandon-我现在明白了。谢谢。向上投票,因为这可能会根据OP的编辑修复OP的问题。仍然存在相同的问题msarchetstrQry=“插入到实践值(“+”“+”+“+”、“+”+“+”+“+”)”);这里的问题是,在提到插入查询时,我无法将字符串值放在大括号中!!!!我现在很高兴!