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

===============>>#1 票数:31 已采纳

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

===============>>#2 票数:16

由于我在这台笔记本电脑上没有代码,所以非常粗略地从内存中:

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

===============>>#3 票数:11

这绝对是一个很好的方法。 但是,如果您碰巧使用支持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());

===============>>#4 票数:7

这是另一种方式(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);

===============>>#5 票数:4

如果您打算阅读大量的列或记录,那么也值得缓存序数并访问强类型方法,例如

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

===============>>#6 票数:3

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

另外需要注意的是,您应该“永远”选择全部,因为如果您向此表添加或删除列,这可能会导致以后出现意外结果。

===============>>#7 票数:1

我想,你可以尝试实体框架。

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

===============>>#8 票数:0

为图书馆充电

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

  ask by Michael Pryor translate from so

未解决问题?本站智能推荐:

关注微信公众号