c# - 连接到数据库

标签 c# database

我正在尝试创建一个类,我可以在我的应用程序中使用它来轻松连接到我的数据库并根据需要运行查询。我找到了 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/

相关文章:

c# - 从附件中获取发件人电子邮件地址

c# - 为什么一个属性被认为是不明确的,而另一个接口(interface)是只设置的?

php - PDO::exec() 阻止进一步的查询工作

mysql - 在 Sequelize 中使用表变量?

sql - 在我的表触发器中记录更改的更有效方法

c# - 如何使用 System.Text.Json 忽略错误值

c# - 多线程应用程序的最后一个线程

c# - 第一次重大部署

c# - Postgresql odbc 驱动程序错误 c# [IM002] [Microsoft][ODBC Driver Manager] 未找到数据源名称

mysql - 从 mySQL 数据库设计表