如何连接到数据库并在C#中遍历记录集?

Translate

在C#中连接和查询数据库以获取一组记录的最简单方法是什么?

This question and all comments follow the "Attribution Required."

所有的回答

Translate

@Goyuix-对于从内存写入的内容非常有用。在这里进行了测试-发现连接没有打开。否则非常好。

using System.Data.OleDb;
...

using (OleDbConnection conn = new OleDbConnection())
{
    conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;";

    using (OleDbCommand cmd = new OleDbCommand())
    {
        conn.Open();
        cmd.Connection = conn;
        cmd.CommandText = "Select * from yourTable";

        using (OleDbDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read())
            {
                Console.WriteLine(dr["columnName"]);
            }
        }
    }
}
来源
Translate

非常粗略地从内存中提取,因为我在这台笔记本电脑上没有代码:

using (OleDBConnection conn = new OleDbConnection())
{
  conn.ConnectionString = "Whatever connection string";

  using (OleDbCommand cmd = new OleDbCommand())
  {
    cmd.Connection = conn;
    cmd.CommandText = "Select * from CoolTable";

    using (OleDbDataReader dr = cmd.ExecuteReader())
    {
      while (dr.Read())
      {
        // do something like Console.WriteLine(dr["column name"] as String);
      }
    }
  }
}
来源
Translate

这绝对是一个好方法。但是,如果您碰巧使用的是支持LINQ to SQL的数据库,那么它会有趣得多。它可能看起来像这样:

MyDB db = new MyDB("Data Source=...");
var q = from db.MyTable
        select c;
foreach (var c in q)
  Console.WriteLine(c.MyField.ToString());
来源
Translate

这是另一种方法(DataReader比这更快):

string s = "";
SqlConnection conn = new SqlConnection("Server=192.168.1.1;Database=master;Connect Timeout=30;User ID=foobar;Password=raboof;");
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 name, dbid FROM sysdatabases", conn);
DataTable dt = new DataTable();

da.Fill(dt);

for (int i = 0; i < dt.Rows.Count; i++)
{
    s += dt.Rows[i]["name"].ToString() + " -- " + dt.Rows[i]["dbid"].ToString() + "\n";
}

MessageBox.Show(s);
来源
Translate

如果您打算读取大量列或记录,则还值得缓存常规并访问强类型方法,例如

using (DbDataReader dr = cmd.ExecuteReader()) {
  if (dr.Read()) {
    int idxColumnName = dr.GetOrdinal("columnName");
    int idxSomethingElse = dr.GetOrdinal("somethingElse");

    do {
      Console.WriteLine(dr.GetString(idxColumnName));
      Console.WriteLine(dr.GetInt32(idxSomethingElse));
    } while (dr.Read());
  }
}
来源
Translate

如果要查询SQL Server数据库(版本7及更高版本),则应将OleDb类替换为System.Data.SqlClient命名空间(SqlConnection, SqlCommandSqlDataReader),因为这些类已经过优化,可以与SQL Server一起使用。

要注意的另一件事是,您不应该“全选”所有内容,因为如果在此表中添加或删除列,这可能会在以后导致意外结果。

来源
Translate

我想,您可以尝试使用实体框架。

using (SchoolDBEntities ctx = new SchoolDBEntities())
{
     IList<Course> courseList = ctx.GetCoursesByStudentId(1).ToList<Course>();
     //do something with courselist here
}
来源
Translate

向图书馆收费

using MySql.Data.MySqlClient;

这是连接:

public static MySqlConnection obtenerconexion()
        {
            string server = "Server";
            string database = "Name_Database";
            string Uid = "User";
            string pwd = "Password";
            MySqlConnection conect = new MySqlConnection("server = " + server + ";" + "database =" + database + ";" + "Uid =" + Uid + ";" + "pwd=" + pwd + ";");

            try
            {
                conect.Open();
                return conect;
            }
            catch (Exception)
            {
                MessageBox.Show("Error. Ask the administrator", "An error has occurred while trying to connect to the system", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return conect;
            }
        }
来源