0

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

5
  • 2
    First off, this looks open to SQL Injection attacks - you should parameterize your queries. Second - what is obj and where does it come from? Commented Nov 20, 2010 at 23:21
  • Your question is far from being understandable. And in any case, beware of concatenating input into your SQL, this calls for SQL injection. Commented Nov 20, 2010 at 23:21
  • 1
    What framework or connector are you using? Commented Nov 20, 2010 at 23:22
  • 2
    (Little Bobby Tables cartoon in 3, 2, ....) Commented Nov 20, 2010 at 23:22
  • So, what type is obj ? Commented Nov 20, 2010 at 23:32

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.