如何使用c#连接到MySQL并在控制台中显示条目列表
本文关键字:控制台 显示 列表 何使用 连接 MySQL | 更新日期: 2023-09-27 18:13:42
如何使用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]);
}
}
}
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();
}
}
}
}
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
有帮助吗?
connectionstring是一个依赖于数据库位置的字符串。sqlcommand中括号内的内容是一个'select *',它将返回所有列。
当你想要写出来的东西,你要么给列名或一个整数。如果你甚至不知道有多少列,你可以设置一个循环,在抛出异常时中断。