应用场景
在txt文件中有很多行用户数据,包括用户名和密码,中间用竖线隔开。如图所示。用界面化的方式,将其全部导入到数据库登录表中。
实现代码
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
//MessageBox.Show(of.ShowDialog().ToString());
if (of.ShowDialog() == DialogResult.OK)
{
txtImport.Text = of.FileName;
}
}
private void btnBegin_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtImport.Text))
{
MessageBox.Show("请选择文件");
}
else
{
//检查文件是否是txt,文件是否存在
//File.Exists();检查是否存在
string[] alllines = File.ReadAllLines(txtImport.Text, Encoding.Default);
//MessageBox.Show(alllines[0]);
//从一个数组里面一个一个往外面取,每循环一次就赋值给item
foreach (string item in alllines)
{
string[] nameandpwd = item.Split('|');
//Console.WriteLine(nameandpwd[0] + " " + nameandpwd[1]);
SqlHelper.Insert(nameandpwd[0], nameandpwd[1]);
}
MessageBox.Show("导入完毕!");
}
}
class SqlHelper
{
public static bool Insert(string name, string pwd)
{
using (SqlConnection conn = new SqlConnection("server=.;database=Test;uid=sa;pwd=jujianfei"))
{
string sql = "insert into Login values(@name,@pwd)";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter sp1 = new SqlParameter("@name", name);
SqlParameter sp2 = new SqlParameter("@pwd", pwd);
cmd.Parameters.Add(sp1);
cmd.Parameters.Add(sp2);
conn.Open();
return cmd.ExecuteNonQuery() > 0;
}
}
}
效果展示

