OpenFileDialog ofd=new OpenFileDialog(); //打开文件选择
if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK)//如果选择的不是打开
{
return;//则返回,结束程序
}
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\File.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();//打开连接
using (SqlCommand cmd = conn.CreateCommand())
{
//cmd.CommandText = "insert into T_person(Name,Age) values (@na,@ag)";
using (FileStream filestream = File.OpenRead(ofd.FileName))//读取文件
{
using (StreamReader streamReaser = new StreamReader(filestream))
{
string line = null;
while ((line = streamReaser.ReadLine()) != null)
{
string[] strs = line.Split(' ');
string name = strs[0];
int age = Convert.ToInt32(strs[1]);
//cmd.Parameters.Add(new SqlParameter("na", name));
//cmd.Parameters.Add(new SqlParameter("ag", age));
cmd.CommandText = "insert into T_person(Name,Age) values ('"+name+"',"+age+")";
MessageBox.Show(cmd.CommandText+","+("影响行数:"+cmd.ExecuteNonQuery()));
//cmd.ExecuteNonQuery();
//cmd.Parameters.Clear();
}
MessageBox.Show("文件导入成功!");
}
}
}
}
请忽略文件导入,主要是怎么都加不到数据库中去,连影响行数都出来了,数据库中死活没有,手动添加没问题。
之前的写的是参数替代,可是发现它怎么都替代不了。。。我真心惆怅了~~~~
|