How to read columns and rows with C#?

╄→尐↘猪︶ㄣ 提交于 2019-12-25 04:55:18

问题


Hello I'm in need of a code to read columns and rows for C#.

I've come this far:

obj.MysqlQUERY("SELECT * FROM `players` WHERE name = "+name+";"); // my query function

Grateful for help;]


回答1:


Here is a standard block of code that I use with MySql a lot. Note that you must be using the MySql connector available here.

string myName = "Foo Bar";
using (MySqlConnection conn = new MySqlConnection("your connection string here"))
{
    using (MySqlCommand cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = @"SELECT * FROM players WHERE name = ?Name;";
        cmd.Parameters.AddWithValue("Name", myName);
        MySqlDataReader Reader = cmd.ExecuteReader();
        if (!Reader.HasRows) return;
        while (Reader.Read())
        {
            Console.WriteLine(GetDBString("column1", Reader);
            Console.WriteLine(GetDBString("column2", Reader);
        }
        Reader.Close();
        conn.Close();
    }
}

private string GetDBString(string SqlFieldName, MySqlDataReader Reader)
{
    return Reader[SqlFieldName].Equals(DBNull.Value) ? String.Empty : Reader.GetString(SqlFieldName);
}

Note that I am using a method to return a specific value if the database value is null. You can get creative and provide various return values or incorporate nullable types, etc.




回答2:


Also you can use:

Create your own dataTable. When reader reaches end, you will have datatable which is custom created, and custom filled by yourself.

DataTable dt = new DataTable();

dt.Columns.Add("Id",typeof(int));

dt.Columns.Add("Name",typeof(string));

dt.Columns.Add("BlaBla",typeof(string));

dt.AcceptChanges();

// Your DB Connection codes.

while(dr.Read())

{
object[] row = new object[]()

{
dr[0].ToString(),// ROW 1 COLUMN 0 

dr[1].ToString(),// ROW 1 COLUMN 1

dr[2].ToString(),// ROW 1 COLUMN 2

}

dt.Rows.Add(row);

}


来源:https://stackoverflow.com/questions/4235552/how-to-read-columns-and-rows-with-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!