[英]CSV File import to SQL Server error
I am working for CSV File import to SQL Server 我正在将CSV文件导入到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(); 我从Internet获得了代码..工作正常,但是当我向该CSV文件添加一个额外的字段(User_Id)时,这给了错误....我无法理解错误在哪里.... 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";
You don't say what the error message is, nor where it occurs, but it seems to me that this line 您没有说错误消息是什么,也不是错误消息在哪里发生,但是在我看来,这一行
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(@Name,@Email,@Mobile," + UserId +")";
should probably be like this 应该大概是这样
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(@Name,@Email,@Mobile,@User_id)";
Replace 更换
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id)
values(@Name,@Email,@Mobile," + UserId +")";
with 与
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id )
values(@Name,@Email,@Mobile,@UserId)";
In the above line, you are just declaring the parameters . 在上面的行中,您只是在声明parameters。
And this is how you actually pass the current user id: 这就是您实际传递当前用户ID的方式:
cmd.Parameters.Add("@User_id", SqlDbType.Int , UserId);
Try this; 尝试这个; hope it will work. 希望它能工作。
值(@ Name,@ Email,@ Mobile,“ + UserId +”)“ //来自ur c的来源
avoid ''+ UserId +'' in your string strSql..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.