Net学习日记_ADO.Net_2_练习(导入练习)

导入练习

主代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InputFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                tbFile.Text = of.FileName;
            }
        }

        private void btnInput_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbFile.Text))
            {
                MessageBox.Show("请选择文件!!");
            }

            string[] allLines = File.ReadAllLines(tbFile.Text,Encoding.Default);

            foreach (string item in allLines)
            {
                string[] napd = item.Split('|');
                SqlHelper.Insert(napd[0],napd[1]);
            }
            MessageBox.Show("导入完毕!!!");

        }
} }

 辅助

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InputFile
{
    class SqlHelper
    {

        public static bool Insert(string name,string pwd)
        {
            using (SqlConnection conn = new SqlConnection("server=PC201609230944\\SQL2005;database=HeiMaBlog;user=sa;pwd=123456"))
            {
                string sql = "insert into UserInfo values(@name,@pwd,default,default)";
                using (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;
                }
            }          
        }
    }
}

数据库

posted @ 2017-10-28 20:17  兽人松  阅读(104)  评论(0编辑  收藏  举报