基本上,我从我设法做的数据库中获取信息。现在我需要获取列名称以显示在控制台应用程序中。我也试图像他们在sql server 2012中显示的那样对齐它们。现在我已经尝试获取列名但它不想工作而且我被卡住了。任何帮助表示赞赏。下面是我的代码。
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net;
namespace sql_connection
{
class Program
{
static void Main(string[] args)
{
string conn = null;
SqlConnection connection;
conn= ("Data Source=database\\SQL2012;Initial Catalog=jobs;User ID=user;Password=passs");
connection = new SqlConnection(conn);
try{
connection.Open();
Console.WriteLine("Connection Open!");
SqlCommand cmd = new SqlCommand("SELECT [jobs].[dbo].[table hours].whd_Date,[jobs].[dbo].[table hours].whd_FromTime,[jobs].[dbo].[table hours].whd_ToTime, [jobs].[dbo].[table hours].whd_User,[jobs].[dbo].[table login].login_Email FROM [jobs].[dbo].[table hours]INNER JOIN [jobs].[dbo].[table login] ON [jobs].[dbo].[table hours].whd_User = [jobs].[dbo].[table login].login_LoginId WHERE DATEDIFF(DAY,[whd_Date],GETDATE())<=7 AND (whd_ToTime = '' OR whd_ToTime IS NULL) AND(whd_User=login_LoginId)");
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
var columns = new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
{
columns.Add(reader.GetName(i));
}
var list = new List<string>();
while(reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
columns.Add(reader.GetName(i));
}
var s = string.Format("{4},{3},{2}, {1}, {0}",
reader["whd_ToTime"] == DBNull.Value? "NULL" : reader["whd_ToTime"].ToString(),
reader["whd_FromTime"] == DBNull.Value? "NULL" : reader ["whd_FromTime"].ToString(),
reader["whd_Date"].ToString(),
reader["whd_User"].ToString(),
reader["login_Email"].ToString());
Console.WriteLine(i);
Console.WriteLine(s);
list.Add(s);
}
var sb = new StringBuilder();
foreach (var s in list)
{
sb.AppendLine(s);
}
connection.Close();
MailAddress to = new MailAddress("email@gmail.com");
MailAddress from = new MailAddress("email@gmail.com");
MailMessage mail = new MailMessage(from, to);
mail.Subject = ("missed punch clock");
mail.Body = sb.ToString();
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new NetworkCredential(
"email@gmail.com", "passworrd");
smtp.EnableSsl = true;
Console.WriteLine("Sending email..");
smtp.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
答案 0 :(得分:1)
Systems.Collections.Generic.List'1[System.String]
是您在.ToString()
上使用List<string>
方法获得的结果,因此我猜测Console.WriteLine(i);
行实际上是Console.WriteLine(list);
。
如果我没错,那么你应该用Console.WriteLine(string.Join(", ", list.ToArray());
要正确对齐输出,您可以使用制表符("\t"
)而不是字符串之间的空格:
var s = string.Format("{4}\t, {3}\t, {2}\t, {1}\t, {0}";
Console.WriteLine(string.Join("\t,", list.ToArray()).TrimEnd(","));
Console.WriteLine(s);