try
{
string CSVFilePathName = textBox4.Text;
for (int i = 0; i < CSVFilePathName.Length; i++)
{
if (CSVFilePathName[i] == '\\')
{
CSVFilePathName.Insert(i + 1, "\\");
}
}
if (string.IsNullOrWhiteSpace(textBox4.Text))
{
MessageBox.Show("Please Select a File");
}
else
{
int count = 0;
// your code here
// string CSVFilePathName = @"'" + textBox4.Text + "'";
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
for (int i = 1; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
for (int f = 0; f < Cols; f++)
{
q = "SELECT * from questions where main_section='" + Fields[0] + "' AND secondary_section='" + Fields[1] + "' AND tert_section='" + Fields[2] + "' AND question='" + Fields[3] + "' AND difficulty='" + Fields[4] + "'";
OleDbCommand cmdn = new OleDbCommand(q, conn);
//MessageBox.Show(q);
object obj = cmdn.ExecuteScalar();
if (obj == null)
{
q = "insert into questions values('" + Fields[0] + "','" + Fields[1] + "','" + Fields[2] + "','" + Fields[3] + "' ,'" + Fields[4] + "')";
OleDbCommand cmdn1 = new OleDbCommand(q, conn);
cmdn1.ExecuteNonQuery();
}
else
{
count++;
}
//MessageBox.Show(Fields[f]);
}
}
// dataGridClients.DataSource = dt;
string msg = "Upload successful\n";
if (count > 0)
{
msg=count.ToString()+" Questions missed due to their duplicates in the database.";
}
MessageBox.Show(msg);
}
}
catch (Exception ex)
{
MessageBox.Show("Error is " + ex.ToString());
throw;
}
我正在使用c#winform将csv文件上传到我的ms访问数据库,但是错误很明显&#34;该字段太小而无法接受您尝试添加的数据量。尝试插入或粘贴较少的数据。&#34;现在该怎么办?
答案 0 :(得分:0)
我建议在SQL中指定表字段
INSERT INTO questions (fieldname1, fieldname2, ...) VALUES (...)
使用参数化值而不是直接在字符串中写入值。这也允许您指定数据类型,然后ADO.Net OLE适配器将有希望适当地处理它并插入长文本没有任何问题。转到Read / Write BLOBs ...以获取插入BLOBS的示例。概念和代码示例与插入长文本值非常相关。它演示了如何为查询设置参数。在您的情况下,请使用OleDbType.LongVarWChar
作为长文本字段。