Execute.scalar命令始终返回null [英] Execute.scalar command always returns null

查看:113
本文介绍了Execute.scalar命令始终返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友,



我用C#编写了一个代码来从数据库中获取数据。

Hello friends,

I have written a code in C# to fetch the data from database.

public string GetDatabaseValues(string value)
        {
            string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["RestAPIConnectionString"].ConnectionString;
            string str = "";
            using (SqlConnection myConnection = new SqlConnection(strCon))
            {

                using (SqlCommand cmd = new SqlCommand(@"select Result from Output where Moviename=@0", myConnection))
                {
                    try
                    {
                        myConnection.Open();
                        cmd.Parameters.AddWithValue("@0", value);
                        str = cmd.ExecuteScalar().ToString();


                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                    finally
                    {
                        myConnection.Close();
                        myConnection.Dispose();
                    }
                }
            }
            return str;
        }





我的数据库有值。这里的问题是尽管我的数据库包含正确的值,但ExecuteScalar命令总是发送空值,这导致对象引用设置为空错误。



请帮助在我的代码中找到问题或至少让我知道ExecuteScalar命令的任何替代方法。



我尝试过:



尝试了Execute.Nonquery但失败了。



My database has the values. The problem here is despite my database containing proper values, the ExecuteScalar command is always sending null value and this results in "Object Reference set to null" error.

Please help in finding out the problem in my code or atleast let me know any alternative to ExecuteScalar command.

What I have tried:

tried Execute.Nonquery but failed.

推荐答案

我唯一能想到的就是你的sql提供者不喜欢数字参数名称。尝试将@ 0重命名为@ p0,看看它是否有所作为。

否则代码看起来很好。
The only thing I can think of here is perhaps your sql provider does not like a numeric parameter name. Try renaming "@0" to "@p0", and see if it makes a difference.
Otherwise the code looks fine to me.


使用 Convert.ToString [ ^ ]而不是< a href =https://msdn.microsoft.com/en-us/library/system.object.tostring(v=vs.110).aspx> ToString [ ^ ]

use Convert.ToString [^] instead of ToString[^]
str  = Convert.ToString( cmd.ExecuteScalar());



如果给定条件没有结果 cmd.ExecuteScalar()将重新开始 null value,如果您尝试访问 null对象的成员 这显然会导致对象引用错误



读取此 c# - Convert.ToString()和.ToString()之间的区别[ ^ ]


if there is no result for the given condition cmd.ExecuteScalar() will retun null value and if you try to access a member of a null object which will obviously result in Object reference error

read this c# - Difference between Convert.ToString() and .ToString() [^]


这篇关于Execute.scalar命令始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆