简体   繁体   English

SqlCommand即使数据库中有数据也返回null

[英]SqlCommand returns null even tho there is data in the database

I am looking at my code for a few hours now and I seriously can't seem to be able to find what is wrong. 我正在看我的代码几个小时,但我似乎无法发现错误所在。

The actual problem is that whenever I run my query it seems to be returning a null type also I am sure there is data in the database. 实际的问题是,每当我运行查询时,它似乎都将返回空类型,而且我确定数据库中有数据。

Error given: 错误提示:

An unhandled exception of type 'System.ArgumentNullException' occurred in System.Data.dll

Additional information: Value cannot be null.

I'll paste in some of my code that I use. 我将粘贴一些我使用的代码。

App.Config 应用配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="MarkProject.Properties.Settings.MoviesConnectionString"
            connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MoviesUML.mdf;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

Database.cs (My own class to fetch data from the db, only showing the Select method and my connection string as that's what's giving troubles) Database.cs(我自己的类,用于从数据库中获取数据,仅显示Select方法和我的连接字符串,因为这很麻烦)

Connection String: 连接字符串:

private string connectionString = ConfigurationManager.ConnectionStrings["MarkProject.Properties.Settings.MoviesConnectionString"].ConnectionString;

Select Method: 选择方法:

public DataTable Select(string query, Dictionary<string, object> values = null)
{
    using(SqlConnection myConnection = new SqlConnection(connectionString))
    {
        using(SqlCommand cmd = new SqlCommand(query, myConnection))
        {
            myConnection.Open();

            if(values != null)
            {
                foreach(var item in values)
                {
                    cmd.Parameters.AddWithValue("@" + item.Key, item.Value);
                }
            }

            this._dataAdapter = new SqlDataAdapter(cmd);
            this._dataAdapter.Fill(this._dataTable);

            myConnection.Close();
        }
    }

    return this._dataTable;
}

And the query that I am running that gives the error. 而我正在运行的查询给出了错误。

DataTable movieData = this._db.Select("SELECT Title, Year FROM Movie");

And here is proof that the table is actually populated. 这是表已实际填充的证明。

数据库中的数据证明

It is the reverse of a very common scenario. 这与非常常见的情况相反。 It is always a misunderstanding of the meaning of |DataDirectory| 总是对| DataDirectory |的含义有误解 in a WinForms app. 在WinForms应用中。 The substitution string |DataDirectory| 替换字符串| DataDirectory | points at the BIN\\DEBUG folder (or x86 variant) when you debug your app inside Visual Studio. 在Visual Studio中调试应用程序时,指向BIN \\ DEBUG文件夹(或x86变体)。 So all the commands runs against a database located in that folder. 因此,所有命令都针对该文件夹中的数据库运行。 Usually this creates problem with INSERT, UPDATE or DELETE operation but also the SELECT could be affected if the two databases contains different data. 通常,这会导致INSERT,UPDATE或DELETE操作出现问题,但是如果两个数据库包含不同的数据,则SELECT可能会受到影响。

To resolve it copy the MDF file from your project folder in your BIN\\DEBUG folder, then create a second connection in your Server Explorer. 要解决该问题,请从您的项目文件夹BIN \\ DEBUG文件夹中复制MDF文件,然后在服务器资源管理器中创建第二个连接。 This one points to the database file in the BIN\\DEBUG folder and use it to check if your commands work. 这指向BIN \\ DEBUG文件夹中的数据库文件,并使用它来检查您的命令是否有效。

public DataTable Select(string query, Dictionary<string, object> values = null)
{
    using(SqlConnection myConnection = new SqlConnection(connectionString))
    {
        using(SqlCommand cmd = new SqlCommand(query, myConnection))
        {
            myConnection.Open();

            if(values != null)
            {
                foreach(var item in values)
                {
                    cmd.Parameters.AddWithValue("@" + item.Key, item.Value);
                }
            }

            cmd.CommandType = CommandType.Text;
            sda = new SqlDataAdapter(cmd);
            dt = new DataTable("YourDataTable");
            new SqlDataAdapter(cmd).Fill(dt);            
        }
    }
    return dt
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM