C# 如何在sql表中存储特殊字符?

C# 如何在sql表中存储特殊字符?,c#,sql,ssis,sql-server-2012,C#,Sql,Ssis,Sql Server 2012,我试图在我的sql表(通过SSIS包)中导入值HACKÅS,但它被插入为HACKÅ…S 尝试将数据类型从varchar(max)更改为nvarchar(max)。没有成功 请建议 下面是我的SSIS脚本任务代码块 public void Main() { //Declare new aplication Application importTextFile_app = new Application(); //Create package

我试图在我的sql表(通过SSIS包)中导入值
HACKÅS
,但它被插入为
HACKÅ…S

尝试将数据类型从
varchar(max)
更改为
nvarchar(max)
。没有成功

请建议

下面是我的SSIS脚本任务代码块

public void Main()
    {
        //Declare new aplication
        Application importTextFile_app = new Application();

        //Create package
        Package ImportTextFile_pkg = new Package();

        //Get the File_Path from package variable
        string File_Path;
        File_Path = (string)Dts.Variables["$Package::File_Path"].Value;

        //Get the delimiter value from package variable
        string Delimiter = (string)Dts.Variables["$Package::Delimiter"].Value;
        Delimiter = Delimiter.Replace("\\t", "\t");  
        char[] delimiters = new char[Delimiter.Length];
        delimiters = Delimiter.ToCharArray();

        //Get the Oledb destination connection string from package avriable
        string Oledb_Connection_String;
        Oledb_Connection_String = (string)Dts.Variables["$Package::Oledb_Connection_String"].Value;

        //Set the destination table name
        string Destination_Table_Name;
        Destination_Table_Name = (string)Dts.Variables["$Package::Table_Name"].Value;

        //Assign relevant package name and description - given table name for uniqueness to avoid conccurrency issues
        ImportTextFile_pkg.Name = Destination_Table_Name;
        ImportTextFile_pkg.Description = "Programmatically create an SSIS 2012 package that loads a Flat File Source into OLE DB Destination Using Script Task's C# language";

        //Insert the Data Flow Task with appropriate name and some buffer space for processing of file            
        ImportTextFile_pkg.Executables.Add("STOCK:PipelineTask");
        TaskHost taskHost = ImportTextFile_pkg.Executables[0] as TaskHost;
        MainPipe dataFlowTask = (MainPipe)taskHost.InnerObject;
        taskHost.Name = "Dynamic Data Flow Task";
        taskHost.Properties["DefaultBufferMaxRows"].SetValue(taskHost, "1000000");

        //Insert the Flat File connection
        ConnectionManager connectionManagerFlatFile = ImportTextFile_pkg.Connections.Add("FLATFILE");
        //You can change this path depending on where you have stored the flat file
        connectionManagerFlatFile.ConnectionString = File_Path;
        //Assign name to the flat file connection
        connectionManagerFlatFile.Name = "TXT_FlatFile";
        //Indicate that the flat file is delimited
        connectionManagerFlatFile.Properties["Format"].SetValue(connectionManagerFlatFile, "Delimited");
        //Indicate whether the source file has column headings or not - in this case, our sample data has column headings.
        connectionManagerFlatFile.Properties["ColumnNamesInFirstDataRow"].SetValue(connectionManagerFlatFile, Convert.ToBoolean(true));
        //Indicate that the flat file is text qualified
        connectionManagerFlatFile.Properties["TextQualifier"].SetValue(connectionManagerFlatFile, "\"");

        //Get native Flat File connection 
        RuntimeWrapper.IDTSConnectionManagerFlatFile100 connectionFlatFile = connectionManagerFlatFile.InnerObject as RuntimeWrapper.IDTSConnectionManagerFlatFile100;

        string line;

        //Prepare create table script according to columns in a file
        string create_table_script;
        Destination_Table_Name = "[" + Destination_Table_Name + "]";
        create_table_script = "create table "+Destination_Table_Name+" ( ";

        //Determine the number of columns by reading the sample Flat File - line by line.            
        using (StreamReader file = new StreamReader(File_Path))
        {
            try
            {
                while ((line = file.ReadLine()) != null)
                {
                    //char[] delimiters = new char[] { '|' };
                    string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

                    for (int i = 0; i < parts.Length; i++)
                    {
                        RuntimeWrapper.IDTSConnectionManagerFlatFileColumn100 flatFileCol = connectionFlatFile.Columns.Add() as RuntimeWrapper.IDTSConnectionManagerFlatFileColumn100;
                        create_table_script = create_table_script +" ["+  parts[i] + "] nvarchar(max),";

                        sS_AssignColumnProperties(flatFileCol, parts[i], Delimiter);
                    }
                    //Exit file after reading the first line
                    break;
                }
                create_table_script = create_table_script.Remove(create_table_script.Length - 1);
                create_table_script = create_table_script + ")";
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                file.Close();
            }
        }
        OleDbConnection conn = new OleDbConnection(Oledb_Connection_String);
        conn.Open();
        string commandText = create_table_script;
        OleDbCommand  cmd = new OleDbCommand(commandText, conn);
        cmd.ExecuteNonQuery();
        conn.Close();


        //Edit the last Flat File column delimiter into NewLine instead of a Comma
        connectionFlatFile.Columns[connectionFlatFile.Columns.Count - 1].ColumnDelimiter = Environment.NewLine;

        //Insert Flat File source component
        IDTSComponentMetaData100 componentSource = dataFlowTask.ComponentMetaDataCollection.New();
        componentSource.Name = "FlatFileSource";
        componentSource.ComponentClassID = "DTSAdapter.FlatFileSource";

        //Insert source design-time instance and initialise component
        CManagedComponentWrapper instanceSource = componentSource.Instantiate();
        instanceSource.ProvideComponentProperties();

        //Set source connection
        componentSource.RuntimeConnectionCollection[0].ConnectionManagerID = connectionManagerFlatFile.ID;
        componentSource.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.GetExtendedInterface(connectionManagerFlatFile);

        //Reinitialize Flat File source metadata, 
        instanceSource.AcquireConnections(null);
        instanceSource.ReinitializeMetaData();
        instanceSource.ReleaseConnections();

        //Insert the SQL Server 2008 OLE-DB connection
        ConnectionManager connectionManagerOleDb = ImportTextFile_pkg.Connections.Add("OLEDB");
        connectionManagerOleDb.ConnectionString = string.Format(Oledb_Connection_String);
        connectionManagerOleDb.Name = "OLEDB";
        connectionManagerOleDb.Description = "OLEDB Connection";

        //Insert OLE-DB destination
        IDTSComponentMetaData100 componentDestination = dataFlowTask.ComponentMetaDataCollection.New();
        componentDestination.Name = "OLEDBDestination";
        componentDestination.Description = "OLEDB Destination for the Flat File data load";
        componentDestination.ComponentClassID = "DTSAdapter.OLEDBDestination";

        //Insert destination design-time instance and initialise component
        CManagedComponentWrapper instanceDestination = componentDestination.Instantiate();
        instanceDestination.ProvideComponentProperties();

        //Set destination connection
        componentDestination.RuntimeConnectionCollection[0].ConnectionManagerID = connectionManagerOleDb.ID;
        componentDestination.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.GetExtendedInterface(connectionManagerOleDb);
        //Indicates the name of the database object used to open a rowset
        instanceDestination.SetComponentProperty("OpenRowset", Destination_Table_Name);
        //Specifies the mode used to open the database
        instanceDestination.SetComponentProperty("AccessMode", 3);
        //Specifies options to be used with fast load. Applies only if fast load is turned on
        instanceDestination.SetComponentProperty("FastLoadOptions", "TABLOCK,CHECK_CONSTRAINTS");
        //Indicates whether the values supplied for identity columns will be copied to the destination or not
        //In this case, we have set this property to false
        instanceDestination.SetComponentProperty("FastLoadKeepIdentity", false);
        //Indicates whether the columns containing null willhave null inserted in the destination or not
        //In this case, we have opted no to insert nulls
        instanceDestination.SetComponentProperty("FastLoadKeepNulls", false);
        //Specifies the column code page to use when code page information is unavailable from the data source
        //In this case we used the default - 1252
        instanceDestination.SetComponentProperty("DefaultCodePage", 1252);
        //Specifies when commits are issued during data insertion
        //In this case, we have opted for the default size which is set to 2147483647
        instanceDestination.SetComponentProperty("FastLoadMaxInsertCommitSize", 2147483647);
        //Indicates the number of seconds before a command times out
        //In this case, we have opted for the default value of 0 which indicates an infinite time-out
        instanceDestination.SetComponentProperty("CommandTimeout", 0);
        //Indicates the usage of DefaultCodePage property value when describing the character data
        //In this case, we have opted for the default value of false
        instanceDestination.SetComponentProperty("AlwaysUseDefaultCodePage", false);

        //Connect the Flat File source to the OLE DB Destination component
        dataFlowTask.PathCollection.New().AttachPathAndPropagateNotifications(componentSource.OutputCollection[0], componentDestination.InputCollection[0]);

        //Get input and virtual input for destination to select and map columns
        IDTSInput100 destinationInput = componentDestination.InputCollection[0];
        IDTSVirtualInput100 destinationVirtualInput = destinationInput.GetVirtualInput();
        IDTSVirtualInputColumnCollection100 destinationVirtualInputColumns = destinationVirtualInput.VirtualInputColumnCollection;

        //Reinitialize the metadata, generating exernal columns from flat file columns
        instanceDestination.AcquireConnections(null);
        instanceDestination.ReinitializeMetaData();
        instanceDestination.ReleaseConnections();

        //Select and map destination columns
        foreach (IDTSVirtualInputColumn100 virtualInputColumn in destinationVirtualInputColumns)
        {
            // Select column, and retain new input column
            IDTSInputColumn100 inputColumn = instanceDestination.SetUsageType(destinationInput.ID, destinationVirtualInput, virtualInputColumn.LineageID, DTSUsageType.UT_READONLY);
            // Find external column by name
            IDTSExternalMetadataColumn100 externalColumn = destinationInput.ExternalMetadataColumnCollection[inputColumn.Name];
            // Map input column to external column
            instanceDestination.MapInputColumn(destinationInput.ID, inputColumn.ID, externalColumn.ID);
        }

        //Execute the package or disable the below code if you intend running the package later
        ImportTextFile_pkg.Execute();

        //Finally, save the package - in this case, we have opted to save the package into file system
        //importTextFile_app.SaveToXml(@"D:\newArticle.dtsx", ImportTextFile_pkg, null);

        Dts.TaskResult = (int)ScriptResults.Success;
    }
    private static void sS_AssignColumnProperties(RuntimeWrapper.IDTSConnectionManagerFlatFileColumn100 flatFileCol, string getColName, string getDelim)
    {
        //Assign delimiter
        flatFileCol.ColumnType = "Delimited";
        flatFileCol.ColumnDelimiter = getDelim;
        flatFileCol.TextQualified = true;

        //Indicate column data type - in this case, all the source columns will be set to String Data Type
        flatFileCol.DataType = RuntimeWrapper.DataType.DT_WSTR;
        //Indicate column width - in this case, width of all source columns will be set to a length of 100
        flatFileCol.ColumnWidth = 4000;
        flatFileCol.MaximumWidth = 4000;


        //Assign column name
        RuntimeWrapper.IDTSName100 columnName = flatFileCol as RuntimeWrapper.IDTSName100;
        columnName.Name = getColName.ToString();
    }
public void Main()
{
//宣布新申请
应用程序importTextFile_app=新应用程序();
//创建包
软件包导入xtfile_pkg=新软件包();
//从包变量获取文件路径
字符串文件路径;
File_Path=(字符串)Dts.Variables[“$Package::File_Path”].Value;
//从包变量中获取分隔符值
字符串分隔符=(字符串)Dts.Variables[“$Package::Delimiter”].Value;
Delimiter=分隔符。替换(“\\t”,“\t”);
char[]delimiters=新字符[Delimiter.Length];
delimiters=Delimiter.ToCharArray();
//从包avriable获取Oledb目标连接字符串
字符串Oledb_连接_字符串;
Oledb_连接_字符串=(字符串)Dts.Variables[“$Package::Oledb_连接_字符串”]。值;
//设置目标表名
字符串目的地\表\名称;
Destination_Table_Name=(字符串)Dts.Variables[“$Package::Table_Name”].Value;
//指定相关的包名称和说明-给定表名称以确保唯一性,以避免货币问题
ImportTextFile_pkg.Name=目的地_表格_名称;
ImportTextFile_pkg.Description=“以编程方式创建SSIS 2012包,该包使用脚本任务的C语言将平面文件源加载到OLE DB目标”;
//插入具有适当名称和一些缓冲区空间的数据流任务以处理文件
ImportTextFile_pkg.Executables.Add(“STOCK:PipelineTask”);
TaskHost TaskHost=ImportTextFile_pkg.Executables[0]作为TaskHost;
MainPipe dataFlowTask=(MainPipe)taskHost.InnerObject;
taskHost.Name=“动态数据流任务”;
taskHost.Properties[“DefaultBufferMaxRows”].SetValue(taskHost,“1000000”);
//插入平面文件连接
ConnectionManager connectionManagerFlatFile=ImportTextFile_pkg.Connections.Add(“FLATFILE”);
//您可以根据存储平面文件的位置更改此路径
connectionManagerFlatFile.ConnectionString=文件路径;
//为平面文件连接指定名称
connectionManagerFlatFile.Name=“TXT_FlatFile”;
//指示平面文件是分隔的
connectionManagerFlatFile.Properties[“Format”].SetValue(connectionManagerFlatFile,“分隔”);
//指示源文件是否具有列标题-在本例中,我们的示例数据具有列标题。
connectionManagerFlatFile.Properties[“ColumnNamesInFirstDataRow”].SetValue(connectionManagerFlatFile,Convert.ToBoolean(true));
//指示平面文件是文本限定的
connectionManagerFlatFile.Properties[“TextQualifier”].SetValue(connectionManagerFlatFile,“\”);
//获取本机平面文件连接
RuntimeWrapper.IDTSConnectionManagerFlatFile100 connectionFlatFile=connectionManagerFlatFile.InnerObject作为RuntimeWrapper.IDTSConnectionManagerFlatFile100;
弦线;
//根据文件中的列准备创建表脚本
字符串创建_表_脚本;
Destination_Table_Name=“[”+Destination_Table_Name+“]”;
create_table_script=“create table”+目的地_table_Name+”(“;
//通过逐行读取示例平面文件来确定列数。
使用(StreamReader文件=新StreamReader(文件路径))
{
尝试
{
而((line=file.ReadLine())!=null)
{
//字符[]分隔符=新字符[]{'|'};
string[]parts=line.Split(分隔符、StringSplitOptions.RemoveEmptyEntries);
对于(int i=0;iinsert into your_table (column_name) values (N'HACKÅS')