【问题标题】:How to connect to MySQL using C# and display a list of entries in the console?如何使用 C# 连接到 MySQL 并在控制台中显示条目列表?
【发布时间】:2011-11-06 17:30:55
【问题描述】:

如何使用 C# Visual Studio 从表中选择所有项目?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace MySQLConnection
{ 
class Program
{
    static void Main(string[] args)
    {

            Console.WriteLine(args[0]);

    }
}
}

【问题讨论】:

    标签: c# mysql


    【解决方案1】:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using MySql.Data.MySqlClient;
    
    namespace ConsoleApplication3
    {
        class Program
        {
            public static string db = "server=localhost;database=dsc;uid=root;password=";
            static void Main(string[] args)
            {
                try
                {
                    MySqlConnection con = new MySqlConnection(db);
                    con.Open(); // connection must be openned for command
                    MySqlCommand cmd = new MySqlCommand("Select * FROM `tablename`", con);
                    MySqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        Console.WriteLine(reader.GetString("id") + ": " + reader.GetString("name") + " - " + reader.GetString("hs"));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: "+ex);
                }
                finally
                {
                    con.Close();
                }
            }
        }
    }
    

    【讨论】:

    【解决方案2】:
    SqlConnection conn = new SqlConnection([connectionstring]);
    SqlCommand com1 =  new SqlCommand("Select * from [tablename]",conn);
    conn.Open(); //Open the connection
    SqlDataReader reader = com1.ExecuteReader();
    
    while(Reader.Read()){ //read each row at a time
    
    console.write(reader["columname"].toString]);
    }
    
    conn.Close(); //don't forget to close it after you're done
    

    这有帮助吗?

    连接字符串是一个取决于数据库位置的字符串。 sql命令中括号中的内容是'select *',它将返回所有列。

    当你想写出这些东西时,你要么给出列名,要么给出一个整数。如果你甚至不知道有多少列,你可以放置一个循环,当抛出异常时会中断。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      相关资源
      最近更新 更多