显示输出查询?

时间:2013-01-19 01:23:48

标签: c# mysql console-application

我正在尝试显示查询SELECT * FROM phpbb_topics的输出 我是从C#控制台应用using the MySql connector api运行的 我运行它phpmyadmin时查询工作正常,并给我一个论坛主题列表。

当我远程在C#应用程序中运行时,它似乎什么也没做。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql;
using MySql.Data; 

namespace SqlConsoleSlr
{
    class Program
    {
        static void Main(string[] args)
        {
            MySql.Data.MySqlClient.MySqlConnection mycon =
            new  MySql.Data.MySqlClient.MySqlConnection(GetConnectionString());
            Console.WriteLine(GetConnectionString());

            if (mycon.State != System.Data.ConnectionState.Open)

                try
                {
                    mycon.Open();
                    Console.WriteLine("we're in");
                }

                catch (System.Data.SqlClient.SqlException ex)
                {
                    Console.WriteLine(ex);
                }

                MySql.Data.MySqlClient.MySqlCommand msc = new MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM `phpbb_topics` ");

            Console.WriteLine("completed");  /// gets to here, but doesn't show output of msc

            Console.ReadLine();
        }

        public static string GetConnectionString()
        {
            string hostname = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;";
            string username = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx;";
            string dbname = "xxxxxxxxxxxxxxxxxxxxxxxx;";
            string password = "xxxxxxxxxxxxxxxxxxxxxxxxxxx;";

            string s = "Server=" + hostname + "User=" + username + "Database=" + dbname + "Password=" + password;

            return s; 
        }
    }
}

我需要在查询对象上调用一些方法吗? 我能找到的唯一一个是msc.BeginExecuteReader();,但这似乎也没有改变执行。

2 个答案:

答案 0 :(得分:1)

您需要创建一个MYSQL数据读取器对象。

MySql.Data.MySqlClient.MySqlDataReader read = msqlCommand.ExecuteReader();

然后您可以在read.read()所有记录之后输出记录。

答案 1 :(得分:0)

您必须创建MySQL Data Reader的对象,然后执行该命令。

MySql.Data.MySqlClient.MySqlCommand msc = new MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM `phpbb_topics` ");

    MySql.Data.MySqlClient.MySqlDataReader read = msqlCommand.ExecuteReader();

    if(read != null)
    {
    //Sample output
    while (read.Read())
            {
                int TopicID = Convert.ToInt32(read["Topic_ID"]);
                string TopicName = Convert.ToString(read["Topic_Name"]);
                Console.WriteLine(TopicID.ToString() + " : " + TopicName);
            }

    }