我正在使用VB.NET和SQL Server 2005,我想从数据库中编写一个文本文件,如。
打开文本文件,从数据库中读取数据,然后写入文本文件。
代码。
cmd = New SqlCommand("SELECT ID, Name, Dept from table", con)
dr = cmd.ExecuteReader
While dr.Read()
Dim data As String
data = File.ReadAllText(dr.Item("PersonID"))
File.WriteAllText("D:\test.txt", data)
End While
上面的代码显示错误,如何编写文本文件
VB.NET代码帮助
答案 0 :(得分:6)
在您的代码中,您实际上并没有从数据库中读取数据。试试这个:
Using writer = New StreamWriter("d:\test.txt")
While dr.Read()
Dim id = dr.GetInt32(0)
Dim name = dr.GetString(1)
Dim dept = dr.GetString(2)
writer.WriteLine(String.Format("{0} {1} {2}", id, name, dept))
End While
End Using
答案 1 :(得分:1)
cmd = New SqlCommand("SELECT ID, Name, Dept from table", con)
dr = cmd.ExecuteReader
Dim sb as new StringBuilder
While dr.Read()
''Let's read line by line and Append it to our StringBuilder
sb.AppendLine(
String.Format("{0} | {1} | {2} | {3}",
dr.item("ID"), dr.item("Name"), dr.item("Dept") ))
End While
''Now that we have all data in our StringBuilder, lets put into our file
File.WriteAllLines("D:\test.txt", sb.ToString())
<强> P.S 即可。来自一个C#家伙...请验证代码是否正确:)(C#代码如下)
using (SqlConnection con = new SqlConnection("my Connection String"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT ID, Name, Dept from table";
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder();
while (dr.Read())
// Let's read line by line and Append it to our StringBuilder
sb.AppendLine(
String.Format("{0} | {1} | {2} | {3}",
dr["ID"], dr["Name"], dr["Dept"]));
// Now that we have all data in our StringBuilder, lets put into our file
File.WriteAllLines("D:\test.txt", sb.ToString());
}
}
答案 2 :(得分:0)
File.ReadAllText
如果从文件中读取。
File.WriteAllText
会将所有内容写入文件,覆盖其中的内容。
你需要得到这样的数据:
data = dr.Item("PersonID").ToString()
写作时,您可能想要append the text:
File.AppendAllText("D:\test.txt", data);
更有效的方法是遍历数据,在内存中构建整个数据集(在每行末尾添加换行符),然后使用File.WriteAllText
一次性写入所有数据。我假设数据量不大,因为这种方法将使用更多内存,但会减少磁盘IO。