c#从文件中读取数据并存入数据库的问题

2024-12-14 14:07:29
推荐回答(5个)
回答1:

private void button1_Click(object sender, EventArgs e)
{
con.Open();//con为你的SqlConnection对象
StreamReader sr = new StreamReader(new FileStream("a.txt", FileMode.Open));
while (!sr.EndOfStream)
{
string data = sr.ReadLine().Replace(" ", "");//除去该行数据中的空格
string insertStr = "insert into t1(ziduan)values('" + data.Substring(0, 1) + "')";
SqlCommand insert = new SqlCommand(insertStr, con);
insert.ExecuteNonQuery();
insertStr = "insert into t2(ziduan)values('" + data.Substring(1, 1) + "')";
insert = new SqlCommand(insertStr, con);
insert.ExecuteNonQuery();
insertStr = "insert into t3(ziduan)values('" + data.Substring(2, 1) + "')";
insert = new SqlCommand(insertStr, con);
insert.ExecuteNonQuery();
}
sr.Close();
con.Close();
MessageBox.Show("插入数据已完成!");
}

注意要加上这两个命名空间:
using System.IO;
using System.Data.SqlClient;

回答2:

单元操作都给你了,自己组织吧~
7.读取文件
//using System.IO;
StreamReader s = File.OpenText(%%1);
string %%2 = null;
while ((%%2 = s.ReadLine()) != null){
%%3
}
s.Close();

3.显示表格
//using System.Data;
//using System.Data.SqlClient;
DataSet ds=null;
using (SqlConnection cn = new SqlConnection(%%1))
//ConfigurationManager.ConnectionStrings["db2ConnectionString"].ConnectionString
//Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
{
cn.Open();
cmd=new SqlDataAdapter("Select * From Author",cn);
ds=new DataSet();
cmd.Fill(ds,%%2); //"作者"
MyDataGrid.DataSource=ds.Tables(%%2).DefaultView; //"作者"
MyDataGrid.DataBind();
}

7.执行插入命令
//using System.Data;
//using System.Data.SqlClient;
using (SqlConnection cn = new SqlConnection(%%1))
//ConfigurationManager.ConnectionStrings["db2ConnectionString"].ConnectionString
//Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
{
SqlCommand cmd = new SqlCommand("insert userRegister_t values('"
+ TextBox1.Text + "','" + TextBox2.Text + "')",cn);
cn.Open();
cmd.ExecuteNonQuery();
}

回答3:

你的数据库不要建3张表,用以张表就可以了,只要三个字段保存。

回答4:

就是一个识别出开始的文件吧?存储应该就简单了

用split("\r\n") 把每行分出来,用split(' ')把每个字母分出来

回答5:

IO读取,ADO.NET写入数据库即可。