我尝试使用C#将CSV文件插入SQL数据库。我可以读取csv文件并将其插入表中,但是任何带有嵌入式逗号的字段都无法正确读取。我怎么能解决这个问题呢。 以下是我使用的代码:
protected void UploadFile_Click(object sender, EventArgs e)
{
conStr = "workstation id=" + ServerName + ";packet size=4096;user id=xx;password=" yyyyy ";data source=" blahblah ";persist security info=False;initial catalog=";
conStr = conStr + DB;
string filepath = "D:\\Work\\Sample01.csv";
StreamReader sr = new StreamReader(filepath);
int NrLines = 0;
string[,] mline;
mline = new string[NrLines, 50];
int cntra = 0;
int counter = 0;
using (StreamReader cr = new StreamReader(filepath))
{
while ((cr.ReadLine()) != null)
{
NrLines++;
}
cr.Close();
}
mline = new string[NrLines, 25];
for (int lcounter = 1; (lcounter <= NrLines); lcounter++)
{
string[] sline = sr.ReadLine().Split(',');
//strElem = strElem.Append("");
if (sline != null)
{
for (int c = 0; c < sline.Length; c++)
mline[cntra, c] = sline[c];
cntra++;
}
}
sr.Close();
for (counter = 1; counter < NrLines; counter++)
{
string Date = mline[counter, 0].ToString();
string SiteUD = mline[counter, 1].ToString();
string SiteName = mline[counter, 2].ToString();
string ModelNo = mline[counter, 3].ToString();
string MachID = mline[counter, 4].ToString();
string Manufacture = mline[counter, 5].ToString();
string TotalCashIn = mline[counter, 6].ToString();
string TotalCashOut = mline[counter, 7].ToString();
string NotesIN = mline[counter, 8].ToString();
string CoinsIn = mline[counter, 9].ToString();
string CoinsOut = mline[counter, 10].ToString();
string CoinstoDrop = mline[counter, 11].ToString();
string RemoteCashIn = mline[counter, 12].ToString();
string RemoteCashOut = mline[counter, 13].ToString();
string TotalWin = mline[counter, 14].ToString();
string TotalBet = mline[counter, 15].ToString();
string GGR = mline[counter, 16].ToString();
string GamesPlayed = mline[counter, 17].ToString();
string HandPays = mline[counter, 18].ToString();
string HopperRefill = mline[counter, 19].ToString();
SQL = "INSERT INTO ztrewVNLCemsImport " +
"([Date], [SiteUD], [SiteName], [ModelNo.], [MachID], " +
"[Manufacture], [TotalCashIn], [TotalCashOut], [NotesIN], [CoinsIn], " +
"[CoinsOut], [CoinstoDrop], [RemoteCashIn], [RemoteCashOut], [TotalWin], " +
"[TotalBet], [GGR], [GamesPlayed], [HandPays], [HopperRefill] ) " +
"VALUES " +
"('" + Date + "', '" + SiteUD + "', '" + SiteName + "', '" + ModelNo + "', '" + MachID + "', " +
"'" + Manufacture + "', '" + TotalCashIn + "', '" + TotalCashOut + "', '" + NotesIN + "', '" + CoinsIn + "', " +
"'" + CoinsOut + "', '" + CoinstoDrop + "', '" + RemoteCashIn + "', '" + RemoteCashOut + "', '" + TotalWin + "', " +
"'" + TotalBet + "', '" + GGR + "', '" + GamesPlayed + "', '" + HandPays + "', '" + HopperRefill + "') ";
SQL = SQL.Replace('\t', ' ');
答案 0 :(得分:2)
尝试使用CSV解析器库来读取CSV文件,而不是自己动手。有许多库可用:CSV parser/reader for C#?
在读取CSV数据后,您可以使用ORM或普通ADO.Net将其写回数据库,如您在示例中所使用的那样。如果您自己编写SQL,则应确保在查询中使用SQL参数。这不仅可以保证每种数据类型都能正确存储,而且还可以保护您免受任何恶意内容的侵害(不是您的情况下很可能)。
最简单的解决方案可能是根据您的数据库表使用SqlDataAdapter
。
答案 1 :(得分:0)
Visual Studio 2017
文件->新建->项目-> Visual C#->控制台应用程序(.NET Framework)->文件名:-ImportCSVToSQL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.IO;
namespace ImportCSVToSQL
{
class Program
{
static void Main(string[] args)
{
try
{
using (SqlConnection conn = new SqlConnection(@"Data Source=**ServerName**; User ID = **; Password = **; Integrated Security=false"))
{
conn.Open();
#region create table
using (SqlCommand createTable = new SqlCommand(@"
IF EXISTS(SELECT TOP 1 *
FROM [DatabaseName].[dbo].[TableName])
DROP TABLE [DatabaseName].[dbo].[TableName]
IF NOT EXISTS
(
SELECT *
FROM
sys.schemas s
INNER JOIN sys.tables t ON
t.[schema_id] = s.[schema_id]
WHERE
s.name = 'dbo' AND
t.name = 'TableName'
)
CREATE TABLE [DatabaseName].[dbo].[TableName]
(
createddate varchar(500),
fid0 varchar(500),
fid1 varchar(500),
fid2 varchar(500),
fid3 varchar(500),
fpip varchar(500),
pid varchar(500),
isloggedin varchar(500),
sessionid varchar(500),
source varchar(500),
useragent varchar(500),
jpnumber varchar(500)
)
;
", conn))
{
createTable.ExecuteNonQuery();
}
#endregion
using (var reader = new StreamReader(@"CSV FILE PATH"))
{
Console.WriteLine("******* Uploading Data ...... ***********************");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var data = line.Split(',');
// data[0] data[1]
string query = @"Insert into [DatabaseName].[dbo].[TableName]" + " values ('" + data[0] + "','" + data[1] + "','" + data[2] + "','" + data[3] + "','" + data[4] + "','" + data[5] + "','" + data[6] + "','" + data[7] + "','" + data[8] + "','" + data[9] + "','" + data[10] + "','" + data[11] + "')";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
Console.WriteLine("******* Uploading Data Completed ***********************");
}
conn.Close();
}
}
catch(Exception ex)
{
Console.WriteLine(" \n**************************** Error - " + ex.Message);
}
Console.ReadLine();
}
}
}