从本地文件读取数据保存到数据库

最原始的数据库操作

class Program
    {
        static void Main(string[] args)
        {
            using (StreamReader sr=new StreamReader("222.txt",Encoding.Default))
            {
                string str = "Data Source=.;Initial Catalog=MyItcast;Integrated Security=True";
                using (SqlConnection con=new SqlConnection(str))
                {
                    string sql="insert into test(age,name) values(@age,@name)";
                    SqlParameter[] param = { 
                                           new SqlParameter("@age", System.Data.SqlDbType.Int),
                                           new SqlParameter("@name", System.Data.SqlDbType.NVarChar)
                                           
                                           };
                    using (SqlCommand cmd=new SqlCommand(sql,con))
                    {
                        con.Open();
                        cmd.Parameters.AddRange(param);
                        //读取数据
                        string line = "";
                        while ((line=sr.ReadLine())!=null)
                        {
                           string[]txts= line.Split(',');
                           int age = txts[1].Length == 0 ? -1 : Convert.ToInt32(txts[1]);
                           string name = txts[2].Length == 0 ? "-1" : txts[2];
                            param[0].Value = age==-1?DBNull.Value:(object)age;
                            param[1].Value = name == "-1" ? DBNull.Value : (object)name;
                            cmd.ExecuteNonQuery();
                        }

                    }
                }

            }
            Console.WriteLine("结束了");
            Console.ReadKey();
        }
    }

 

posted @ 2016-06-08 11:33  .追风逐月  阅读(599)  评论(0编辑  收藏  举报