我在连接 SQL 和运行一个简单的选择查询时遇到困难,我需要将 select * from ServerInfo where ServerID = 1991638835"
输出到控制台行或 txt 文件:
这是我的代码:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Text;
namespace ConnectingToSQLC
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("server= XXXXX; database = ES1Archive; Integrated Security=false; User ID = sa; Password=XXXXXX");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from ServerInfo where ServerID = 1991638835", conn);
SqlDataReader reader = cmd.ExecuteReader ();
while (reader.Read())
{
//Console.WriteLine ("{1}", "{0}", reader.GetString (0), reader.GetString (1));
Console.WriteLine(reader.GetString(3));
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
}
}
它工作正常。但是如果我改成
Console.WriteLine("{1}", "{3}", reader.GetString (1), reader.GetString (3));
我总是有第 2 列。总共有 7列,第 3 列为空,而第 4 列为 XML。
如何修改我的代码以转储所有内容?
最佳答案
您的格式字符串太多 - 将它们组合成一个,例如:
Console.WriteLine ("{0} - {1}", reader.GetString(1), reader.GetString(3))
Console.WriteLine
格式字符串的索引overload you are using就像string.Format
- 它不依赖于您在阅读器中使用的哪些索引,格式参数占位符只需要匹配其他 params args
的顺序参数。
还有:
- 使用
SELECT *
是不好的做法通常,当您按序号索引访问数据阅读器列时更加危险,因为表中的更改会破坏您的阅读器代码。相反,建议您显式命名您正在使用的列和/或使用reader
的列名访问器 - 如果阅读器的唯一用途是在
Console.WriteLine
上输出字符串, 你不需要使用Get<Type>()
重载 - 您可以简单地使用序数访问器(在您保证具有显式列名SELECT
的列的顺序之后:-)
例如对于读者第 1、3 和 6 列(当然是零基础):
Console.WriteLine ("{0} - {1} - {2}", reader[1], reader[3], reader[6]);
但更好的是:
Console.WriteLine ("{0} - {1} - {2}", reader["RealNameOfCol1"],
reader["RealNameOfCol3"], reader["RealNameOfCol6"]);
关于C# SQL Select Query 只转储一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30622863/