数据库字段与类型
id int,Name nvarchar(20),Age int
TXT文本内容为
小高-20
张三-18
李四-19
private void btnInput_Click(object sender, EventArgs e)
{
if (opFile.ShowDialog() != DialogResult.OK) //判断用户点击 确定 还是 取消,不点确定,则返回程序
{
return;
}
using(FileStream FStream = File.OpenRead(opFile.FileName)) //打开文件进行读取
{
//定义字符编码为GB2312
using (StreamReader stremReader = new StreamReader(FStream,Encoding.GetEncoding("GB2312")))
{
using (SqlConnection conn = new SqlConnection(@"server=.;database=mytest;uid=sa;pwd=gao"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "insert into T_Age(Name,Age) values(@N,@A)";
string line = null; while ((line = stremReader.ReadLine()) != null) //读取文本中一行数据,当不为空时
{
string[] strs = line.Split('-'); // 按"-"符分割字符串
string name = strs[];
int age = Convert.ToInt32(strs[]);
cmd.Parameters.Clear(); //参数不能重复添加,在while中一直用的是这个SqlCommand对象
cmd.Parameters.Add(new SqlParameter("@N", name));
cmd.Parameters.Add(new SqlParameter("@A", age));
cmd.ExecuteNonQuery();
}
}
}
}
MessageBox.Show("导入成功!");
}
}