C#에서 데이터베이스에 연결하고 레코드세트를 반복하려면 어떻게 해야 하나요?

StackOverflow https://stackoverflow.com/questions/930

  •  08-06-2019
  •  | 
  •  

문제

C#에서 레코드 집합에 대해 데이터베이스를 연결하고 쿼리하는 가장 간단한 방법은 무엇입니까?

도움이 되었습니까?

해결책

@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"]);
            }
        }
    }
}

다른 팁

이 노트북에 코드가 없기 때문에 매우 대략적이고 기억에 남는 내용입니다.

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);
      }
    }
  }
}

그것은 확실히 좋은 방법입니다.그러나 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());

이는 다른 방법입니다(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);

많은 수의 열이나 레코드를 읽으려는 경우 서수를 캐시하고 강력한 형식의 메서드에 액세스하는 것도 좋습니다.

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());
  }
}

SQL Server 데이터베이스(버전 7 이상)를 쿼리하는 경우 OleDb 클래스를 해당 클래스로 바꿔야 합니다. 시스템.데이터.Sql클라이언트 네임스페이스(SQLConnection, SQL명령 그리고 SQLDataReader) 해당 클래스는 SQL Server에서 작동하도록 최적화되었기 때문입니다.

또 한 가지 주의할 점은 나중에 이 테이블에 열을 추가하거나 제거할 경우 예상치 못한 결과가 발생할 수 있으므로 모두 선택하면 '절대로' 안 된다는 것입니다.

제 생각에는 엔터티 프레임워크를 사용해 볼 수 있을 것 같습니다.

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

도서관에 충전하세요

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;
            }
        }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top