0

I am working for CSV File import to SQL Server

I got code from Internet ..working fine But when I am adding one extra field (User_Id) with that CSV file to SQL then this is giving error ....I am not able to understand where is doing mistake ....code... DataTable tblReadCSV = new DataTable();

            tblReadCSV.Columns.Add("Name");
            tblReadCSV.Columns.Add("Email");
            tblReadCSV.Columns.Add("Mobile");

            tblReadCSV.Columns.Add("User_id");
            string path = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);

            FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Email/UploadFile/" + path));
            path = Server.MapPath("~/Email/UploadFile/" + path);
            TextFieldParser csvParser = new TextFieldParser(path);
             csvParser.Delimiters = new string[] { "," };
            csvParser.TrimWhiteSpace = true;
            csvParser.ReadLine();

            while (!(csvParser.EndOfData == true))
            {
                tblReadCSV.Rows.Add(csvParser.ReadFields());
            }
            string strCon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
            string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(@Name,@Email,@Mobile," + UserId +")";
            SqlConnection con = new SqlConnection(strCon);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = strSql;
            cmd.Connection = con;               
            cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50, "Name");
            cmd.Parameters.Add("@Email", SqlDbType.VarChar, 50, "Email");
            cmd.Parameters.Add("@Mobile", SqlDbType.VarChar, 50, "Mobile");

            cmd.Parameters.Add("@User_id", SqlDbType.Int , UserId);

            SqlDataAdapter dAdapter = new SqlDataAdapter();
            dAdapter.InsertCommand = cmd;
            int result = dAdapter.Update(tblReadCSV);
            Label1.Text = "File successfully uploaded";
4

3 回答 3

0

values(@Name,@Email,@Mobile," + UserId +")"// source from ur c

avoid ''+ UserId +'' in your string strSql..
于 2014-08-20T12:17:36.767 回答
0

你没有说错误信息是什么,也没有说它发生在哪里,但在我看来,这条线

string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(@Name,@Email,@Mobile," + UserId +")";

应该是这样的

string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(@Name,@Email,@Mobile,@User_id)";
于 2013-05-27T15:30:14.077 回答
0

代替

string strSql = "Insert into Contacts(Name,Email,Mobile,User_id)
values(@Name,@Email,@Mobile," + UserId +")";

string strSql = "Insert into Contacts(Name,Email,Mobile,User_id )
values(@Name,@Email,@Mobile,@UserId)";

在上面的行中,您只是声明了参数。

这就是您实际传递当前用户 ID 的方式:

cmd.Parameters.Add("@User_id", SqlDbType.Int , UserId);

尝试这个; 希望它会奏效。

于 2013-05-27T15:49:08.583 回答