1 { 90 #endregion 91 #region 数据导入 92 string constr = "data source=.;initial catalog=itcast2013;integrated security=true"; 93 using (StreamReader sr = new StreamReader(@"f:\person.txt")) 94 { 95 using (SqlConnection con = new SqlConnection(constr)) 96 { 97 string sqlstr = "insert into tblperson values(@uname,@uage,@uheight)"; 98 using (SqlCommand cmd = new SqlCommand(sqlstr, con)) 99 { 100 //使用带参数的sql语句时,不要把增加参数的代码写在循环中...否则就重复增加参数啦 101 //解决思路:先声明参数对象,不赋值,在循环里再赋值.如下 102 SqlParameter[] spt = new SqlParameter[] 103 { 104 new SqlParameter("@uname",System.Data.SqlDbType.NVarChar,50), 105 new SqlParameter ("@uage",System.Data.SqlDbType.Int), 106 new SqlParameter("@uheight",System.Data.SqlDbType.Int) 107 }; 108 //添加参数 109 cmd.Parameters.AddRange(spt); 110 111 string line = sr.ReadLine(); 112 con.Open(); 113 while ((line = sr.ReadLine()) != null) 114 { 115 string[] parts = line.Split(','); 116 //Console.WriteLine("{0}, {1}, {2} ,{3}",parts[0],parts[1],parts[2],parts[3]); 117 string uname = parts[1]; 118 int uage = parts[2].Length > 0 ? Convert.ToInt32(parts[2]) : -1; 119 int uheight = parts[3].Length > 0 ? Convert.ToInt32(parts[3]) : -1; 120 //给参数赋值 121 spt[0].Value = uname; 122 spt[1].Value = uage == -1 ? DBNull.Value : (object)uage; 123 spt[2].Value = uheight == -1 ? DBNull.Value : (object)uheight; 124 cmd.ExecuteNonQuery(); 125 126 //如果想要在循环中增加参数,需要每次执行完毕之后再清空一下 127 //cmd.Parameters.Clear(); 128 } 129 130 } 131 } 132 } 133 #endregion 134 Console.ReadKey(); 135 }