我正在尝试创建一个类,我可以在我的应用程序中使用它来轻松连接到我的数据库并根据需要运行查询。我找到了 this发布,但它并没有像我预期的那样工作。
这是我的类(class):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
//a class that returns a connection to the database
namespace epaCUBE_Utility_Tool
{
public class epaCUBE_DB
{
public static SqlConnection GetConnection()
{
string str = "user id=MyUserName;" +
"password=MyPassword;server=myServer;" +
"database=myDatabase; " +
"connection timeout=30";
SqlConnection con = new SqlConnection(str);
con.Open();
return con;
}
}
}
下面是我尝试使用它的方式:
private void button1_Click(object sender, EventArgs e)
{
var connection = epaCUBE_DB.GetConnection();
connection.Open();
SqlDataReader rdr = null;
string CommandText = "SELECT Field1, Field2 FROM TableName";
SqlCommand cmd = new SqlCommand(CommandText, connection);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
this.comboBox1.Items.Add(rdr["Field1"].ToString() +
": " + rdr["Field2"].ToString());
}
connection.Close();
}
当我按下按钮时出现错误
InvalidOperationException:连接未关闭。连接的当前状态是打开的。
我做错了什么? 谢谢, 张国荣
最佳答案
GetConnection
为您调用了 Open
,但您在调用 GetConnection
之后再次手动调用它。在 GetConnection
内部或外部调用它,但不能同时在这两个地方调用它。
关于c# - 连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17824610/