从文本文件向数据库内插入数据(openfiledialog等控件)

如上图所示布局,拖一个openfiledialog控件到面板,设置Filter属性为:文件文件|*.txt

数据库布局如下图:

浏览按钮的代码:

<textarea cols="50" rows="15" name="code" class="c-sharp"> if (ofdlog.ShowDialog() == DialogResult.OK) { txtfilename.Text = ofdlog.FileName; } </textarea>

插入按钮的代码:

<textarea cols="50" rows="15" name="code" class="c-sharp"> if (string.IsNullOrEmpty(txtfilename.Text)==false) { using (SqlConnection conn = new SqlConnection()) { //计数器 int count = 0; conn.ConnectionString = @"Data Source=./SQLEXPRESS;AttachDBFilename=|DataDirectory|/persons.mdf;Integrated Security=True;User Instance=True"; conn.Open(); string[] lines = File.ReadAllLines(txtfilename.Text); foreach (var line in lines) { string[] strs = line.Split('|'); string name = strs[0]; int scores = Convert.ToInt32(strs[1]); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from T_person where pname=@ne and pscores=@ss"; cmd.Parameters.AddWithValue("ne", name); cmd.Parameters.AddWithValue("ss", scores); SqlDataReader reader = cmd.ExecuteReader(); bool find = reader.Read(); reader.Dispose(); //先查询有没有此条数据,如果没有则插入 if (find == false) { cmd.CommandText = "insert into T_person values(@pname,@pscores)"; cmd.Parameters.AddWithValue("pname", name); cmd.Parameters.AddWithValue("pscores", scores); cmd.ExecuteNonQuery(); count++; } } MessageBox.Show(count+"条数据插入完毕"); } } else { MessageBox.Show("请先打开数据文件"); txtfilename.Focus(); } </textarea>

你可能感兴趣的:(数据库,String,Security,filter,cmd,insert)