开发者

How to read columns and rows with C#?

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


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.


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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜