将记事本中的数据导入数据库(winform)

来源:互联网 发布:sent it 编辑:程序博客网 时间:2024/05/04 02:06
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;


namespace 将记事本中的数据导入数据库_winform_
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            //导出文本文件中的内容
            StreamReader sr = new StreamReader(new FileStream(@"G:\1.txt", FileMode.Open, FileAccess.Read), System.Text.Encoding.Default);
            string sLine = "";
            ArrayList al = new ArrayList();
            
            //foreach (string sOutput in al)
            //    MessageBox.Show(sOutput);
            //连接数据库
            string connstr = ConfigurationManager.ConnectionStrings["strcon"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connstr))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    


                    while (sLine != null)
                    {
                        
                        sLine = sr.ReadLine();
                        if (sLine != null)
                            al.Add(sLine);
                    }
                    sr.Close();
                    foreach (string sOutput in al)
                    {


                        string[] strs = sOutput.Split('|');
                        string name ="'"+ strs[0]+"'";
                        string phone = strs[1];
                        string address = "'" + strs[2] + "'";
                        string age = strs[3];
                        string sex = "'" + strs[4] + "'";
                        cmd.CommandText = "insert into T_StudentsInfo(name,phone,address,age,sex)values("+name+","+phone+","+address+","+age+","+sex+")";
                        //cmd.Parameters.AddWithValue("@username", name);
                        //cmd.Parameters.AddWithValue("@phone", Convert.ToInt32(phone));
                        //cmd.Parameters.AddWithValue("@address", address);
                        //cmd.Parameters.AddWithValue("@age", Convert.ToInt32(age));
                        //cmd.Parameters.AddWithValue("@sex", sex);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            MessageBox.Show("导成功了");
        }
    }
}
原创粉丝点击