793291696servertotxt-爱代码爱编程
server to txt
首先定义了连接字符串connStr和查询语句query。然后使用SqlConnection类和SqlCommand类连接数据库,并执行查询语句,获取到SqlDataReader对象reader。接着使用StreamWriter类将数据写入txt文件,使用String.Format方法将每行数据格式化后写入txt文件中。
program.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace readtxttoxml
{
internal class Program
{
static void Main(string[] args)
{
string connStr = "Data Source=localhost;Initial Catalog=scnt;Integrated Security=True;";
string query = "SELECT * FROM student";
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
// Write data to txt file
using (StreamWriter writer = new StreamWriter("D:/DDD/students.txt"))
{
while (reader.Read())
{
string data = String.Format("{0}\t{1}\t{2}\t", reader["ID"], reader["Name"], reader["Gender"]);
writer.WriteLine(data);
}
}
}
}
}
}
}