I can select the number of rows returned by a query when I select everything by doing the following:
SELECT Count(*) FROM `foo`.`bar`;
However, I now want to select how many columns are returned. Is there an easy way to do this?
Use the information_schema database.
SELECT
COUNT(COLUMN_NAME) AS numcols
FROM COLUMNS
WHERE
TABLE_NAME = 'bar'
AND TABLE_SCHEMA = 'foo'
To put the two together, use:
SELECT
(SELECT COUNT(*) FROM foo.bar) AS numrows,
(SELECT
COUNT(COLUMN_NAME) AS numcols
FROM COLUMNS
WHERE
TABLE_NAME = 'bar'
AND TABLE_SCHEMA = 'foo'
) AS numcols
DESCRIBE someTable and then mysql_count_rows() on the result.
Since the question has to do with C#, I think this should work - but I haven't done C# in a long time.
MySqlConnection connection = new MySqlConnection(#...);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "DESCRIBE sometable";
connection.Open();
Reader = command.ExecuteReader();
Reader.FieldCount # this has the count of rows, and hence columns
If your table mydb.mytable is MyISAM, the following should work well:
SELECT
row_count,column_count
FROM
(
SELECT table_rows row_count
FROM information_schema.tables
WHERE table_schema = 'mydb'
AND table_name = 'mytable'
) rowcount,
(
SELECT MAX(ordinal_position) column_count
FROM information_schema.columns
WHERE table_schema = 'mydb'
AND table_name = 'mytable'
) columncount
;
SHOW COLUMNS FROM foo.bar;should do the trick.