MySQL 错误:“填充:SelectCommand.Connection 属性尚未初始化。”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5750554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error : "Fill: SelectCommand.Connection property has not been initialized."
提问by Wahtever
im getting this error while trying to connect a mysql database to an editor, here is the code behind:
我在尝试将 mysql 数据库连接到编辑器时遇到此错误,这是后面的代码:
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
MySqlConnection conn = new MySqlConnection(@"connection string");//tested and working
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT tes FROM ins");
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.SelectCommand = cmd;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Editor1.Content = dt.Rows[0]["tes"].ToString();
}
conn.Close();
}
and here is the aspx page code:
这是aspx页面代码:
<body>
<form id="form1" runat="server">
<cc1:Editor ID="Editor1" runat="server" Height="400px" Visible="true" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
what am i doing wrong, thanks in advance.
我做错了什么,提前致谢。
i am using asp.net 3.5.
我正在使用 asp.net 3.5。
回答by Rune Grimstad
Change the line
换线
MySqlCommand cmd = new MySqlCommand("SELECT tes FROM ins");
To
到
MySqlCommand cmd = new MySqlCommand("SELECT tes FROM ins", conn);
And it should work.
它应该工作。
Alternatively assign conn to the cmd.Connection property.
或者将 conn 分配给 cmd.Connection 属性。
The problem with your code is that you never assign a connection to the command, hence the error saying that the connection is not initialized.
您的代码的问题在于您从未为命令分配连接,因此错误提示连接未初始化。
回答by Palnati
Try This
尝试这个
MySqlCommand cmd = new MySqlCommand("SELECT tes FROM ins",conn);
or
或者
MySqlCommand cmd = new MySqlCommand("SELECT tes FROM ins");
cmd.Connection=conn;
回答by Vishal Agrawal
I got also this problem. after search the problem found that the object of connection that i have provide SqlDataAdapter is not Initialize so the connection passed as null
我也遇到了这个问题。搜索后发现问题是我提供的SqlDataAdapter的连接对象没有初始化,所以连接传递为空
回答by FUSION CHA0S
Had this same error and simply just forgot the connection in the SQL string as mentioned above. Just needed to add conafter the comma.
有同样的错误,只是忘记了上面提到的 SQL 字符串中的连接。只需要在逗号后添加con。