今天2007年八月28日写的读取文本文件中的列名和数据进sql server数据库

来源:互联网 发布:网络智能家居公司 编辑:程序博客网 时间:2024/05/16 08:54

guid*name*level*color*diffculty*type*giver_dlg*direct_desc*unfinish_desc*receiver_dlg*rewardItems_and*rewardItems_or*rewardMoney*rewardExp*rewardRank*guildLevel*guildContribute*guildExp*dlg_npc_entry0*dlg_content0*dlg_npc_entry1*dlg_content1*dlg_npc_entry2*dlg_content2*dlg_npc_entry3*dlg_content3*dlg_npc_entry4*dlg_content4
1*青龙圣使*25*1*1*QT_Main*    <tab />传闻邪恶的青龙及七星宿正觉醒于这片土地,他们受到了黑暗的蛊惑,正逐渐沦为邪恶的爪牙,在一切还可以控制前,我们必须将他们彻底消灭。    <n />    <tab />青龙玉是寄宿着神秘力量的玉牌,也是我一直致力于收集的宝物,如果你可以把它拿来给我,我可以给予你各种奖励,你拿来的数量越多,我可以提供给你越优异的奖励。    <n />*寻找并消灭青龙七星宿,将他们携带的青龙玉交给青龙使者*    <tab />*    <tab />很好,这是你的奖励。***0*0.0*0*0*0*0.0*0**0**0**0**0* 

这个是源文件,第一行为列名的拼接,是用星号分割,第二,三为内容,但是首先我不知道这个txt文件的字符集编码,是unicode还是bcunicode,所以我借鉴了网上高手的一类

 

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace split
{
    
class TxtFileEncoding
    
{
        
public TxtFileEncoding()
        
{
            
//
            
// TODO:在此处添加构造函数逻辑
            
//
        }

        
/// <summary>
        
/// 取得一个文本文件的编码方式。如果无法在文件头部找到有效的前导符,Encoding.Default将被返回。
        
/// 
        
/// </summary>
        
/// <param name="fileName">文件名</param>
        
/// <returns></returns>

        public static Encoding GetEncoding(string fileName)
        
{
            
return GetEncoding(fileName, Encoding.Default);  
        }

        
/// <summary>
        
/// 取得一个文本文件流的编码方式。
        
/// </summary>
        
/// <param name="stream">文本文件流。</param>
        
/// <returns></returns>

        public static Encoding GetEncoding(FileStream stream)
        
{
            
return GetEncoding(stream, Encoding.Default);
        
        }

        
/// <summary>
        
/// 取得一个文本文件的编码方式。
        
/// </summary>
        
/// <param name="fileName">文件名。</param>
        
/// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param>
        
/// <returns></returns>

        public static Encoding GetEncoding(string fileName, Encoding defaultEncoding)
        
{
            FileStream fs 
= new FileStream(fileName, FileMode.Open);
            Encoding targetEncoding 
= GetEncoding(fs, defaultEncoding);
            fs.Close();
            
return targetEncoding;
        }

        
public static Encoding GetEncoding(FileStream stream, Encoding defaultEncoding)
        
{
            Encoding targetEncoding 
= defaultEncoding;
            
if (stream != null && stream.Length >= 2)
            
{
                
//保存文件流的前4个字节
                byte byte1 = 0;
                
byte byte2 = 0;
                
byte byte3 = 0;
                
byte byte4 = 0;
                
//保存当前Seek位置
                long origPos = stream.Seek(0, SeekOrigin.Begin);
                stream.Seek(
0, SeekOrigin.Begin);
                
int nByte = stream.ReadByte();
                byte1 
= Convert.ToByte(nByte);
                byte2 
= Convert.ToByte(stream.ReadByte());
                
if (stream.Length >= 3)
                
{
                    byte3 
= Convert.ToByte(stream.ReadByte());

                }

                
if (stream.Length >= 4)
                
{
                    byte4 
= Convert.ToByte(stream.ReadByte());
                }

                
//根据文件流的前4个字节判断Encoding
                
//Unicode {0xFF,0xFE};
                
//BE-Unicode {oxFE,0xFF};
                
//UTF8={0xEF,0xBB,0xBF};
                if (byte1 == 0xFE && byte2 == 0xFf)//UnicodeBe
                {
                    targetEncoding 
= Encoding.BigEndianUnicode;

                }

                
if (byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)// Unicode
                {
                    targetEncoding 
= Encoding.Unicode;
                }

                
if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)//UTF8
                {
                    targetEncoding 
= Encoding.UTF8;
                }

                
//恢复Seek位置
                stream.Seek(origPos, SeekOrigin.Begin);
            }

            
return targetEncoding;
        }

    }

}

之后是我的源文件,开始想的是以前用过的c#管道命令proess执行osql操作脚本,或者用sqldmo(此为sql server2000的对象模型),在sql server2005就变成了smo,后来公司一个高手指点,用了sqlhelper

 

using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Collections;
//using STONE.HU.HELPER.UTIL;
namespace GMSERVER.Logic
{

    
/**//// <summary>
    
/// Summary description for SqlSvrHelper.
    
/// </summary>

    public class SqlHelper
    
{
        
private static string auUserID = null;
        
private static string  auPwdID = null;
        
private string url = null;
        
private string userID = null;
        
private string pwd = null;
        
//public static Log log = null;
        public static string ConnectionString="";
        
public SqlHelper()
        
{

        }

        
public static string GetConnectionString(bool includedb,string host,string userName,string passwd,string dbName)
        
{
            
if (includedb)
                
return String.Format("server={0};user id={1};password={2};database={3};" +
                    
"pooling=false;charset=gb2312", host,userName,passwd,dbName);
            
return String.Format("server={0};user id={1};password={2};" +
                
"persist security info=true;", host, userName, passwd);
        }

        
public void init(string url,string dbName,string userID,string pwd)
        
{
            
string path= AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            
//log = new Log(path+"/log.txt", true, false, 0);    
            ConnectionString = "Data Source="+url+";Initial Catalog="+dbName+";User ID="+userID+";Password="+pwd+";Pooling=true;Min Pool Size=0;Max Pool Size=10;Connect Timeout=180";
        }

        
public static int insertGMtoolsLog(int userID,string gameName,string serverIP,string sp_name,string RealAct)
        
{
            
int result = -1;
            SqlParameter[] paramCode;
            
try
            
{
                paramCode 
= new SqlParameter[6]{
                                                   
new SqlParameter("@Gm_UserID",SqlDbType.Int),
                                                   
new SqlParameter("@Gm_GameName",SqlDbType.VarChar,30),
                                                   
new SqlParameter("@Gm_ServerIP",SqlDbType.VarChar,30),
                                                   
new SqlParameter("@Gm_SPname",SqlDbType.VarChar,30),
                                                   
new SqlParameter("@Gm_RealAct",SqlDbType.VarChar,500),
                                                    
new SqlParameter("@result",SqlDbType.Int)}
;
                paramCode[
0].Value=userID;
                paramCode[
1].Value=gameName;
                paramCode[
2].Value=serverIP;
                paramCode[
3].Value=sp_name;
                paramCode[
4].Value=RealAct;
                paramCode[
5].Direction = ParameterDirection.ReturnValue;
                SqlHelper.ExecSPCommand(
"sp_InsertGMtoolslog",paramCode);
            }

            
catch(SqlException ex)
            
{
                Console.WriteLine(ex.Message);
            }

            
return result;

        }

        
GetDataSet
         
ExecCommand       
        
ExecuteScalar
        
ExecSPCommand
        
ExecSPCommand
        
ExecSPDataSet ExecSPDataSet
        
ExecSPDataSet DbType
        
DbType UpdateTable
        
UpdateTable InsertTable
        
InsertTable updateRow
        
updateRow deleteRow
        
deleteRow midifyRow
        
midifyRow insertRow

        
insertRow
        
commitTrans
        
commitTrans
        
transcation
        
URL
        
USERID
        
PWD
        
AUUser
        
AUPWD
    }

}


这个是微软著名的数据库访问的中间件,在很多软件公司和学校里都接触过,petshop中也运用到了.

下面是我写的代码:

 

 Encoding fileEncoding = TxtFileEncoding.GetEncoding("a.txt", Encoding.GetEncoding("GB2312"));
            TextReader streamReader 
= new StreamReader("a.txt",fileEncoding);
            
//streamReader.ReadToEnd();
            SqlHelper mysqlhelper = new SqlHelper();
            mysqlhelper.init(
".""master""sa""sa");
            
            
string a;
            
string[] totalrow;
            a
=streamReader.ReadLine();
            totalrow 
= a.Split(new Char[] '*' });
            streamReader.Close();
            streamReader 
= new StreamReader("a.txt", fileEncoding);
            System.Data.DataTable bc 
= new DataTable();
            
int j=0;
            DataTable table 
= new DataTable("temptable");

           
//  Add all column objects to the table.
            for (int i = 0; i < totalrow.Length; i++)
            
{
                DataColumn idColumn 
= new DataColumn();
                idColumn.DataType 
= System.Type.GetType("System.String");
                idColumn.ColumnName 
= totalrow[i];
                table.Columns.Add(idColumn);

            }

            
while ((a=streamReader.ReadLine()) != null)
            
{
                
                
string[] split = a.Split(new Char[] '*' });
               
if(j==0)
             
{
                 
                 StringBuilder InsertTableSql 
= new StringBuilder();
                 InsertTableSql.Append(
"CREATE TABLE temptable(");
                 
for (int i = 0; i < split.Length; i++)
                 
{
                     
if (i == 0)
                     
{
                         InsertTableSql.Append(split[i]);
                         InsertTableSql.Append(
" int PRIMARY KEY ");
                     }

                     
else
                     
{
                         InsertTableSql.Append(split[i]);
                         InsertTableSql.Append(
" varchar(500)");
                     }

                 
if((i+1)!=split.Length)
                             InsertTableSql.Append(
",");
                 }

                 InsertTableSql.Append(
")");
                 SqlCommand sqlcom 
= new SqlCommand();
                 sqlcom.CommandText 
= InsertTableSql.ToString();
                 
try
                 
{
                     SqlHelper.ExecCommand(sqlcom);
                 }

                 
catch (Exception ex)
                 
{
                     
throw ex;
                     MessageBox.Show(ex.Message);
                 }
              

             }

             
else
             
{
                 StringBuilder InsertTableSql 
= new StringBuilder();
                 InsertTableSql.Append(
"INSERT INTO temptable (");
                 
for (int i = 0; i < totalrow.Length; i++)
                 
{
                     
                     InsertTableSql.Append(totalrow[i]);
                     
if ((i + 1!= totalrow.Length)
                         InsertTableSql.Append(
",");

                 }

                 InsertTableSql.Append(
") values('");
                 
for (int i = 0; i < split.Length; i++)
                 
{
                     InsertTableSql.Append(split[i]);
                     
if ((i + 1!= split.Length)
                         InsertTableSql.Append(
"','");

                 }

                 InsertTableSql.Append(
"')");
                 SqlCommand sqlcom 
= new SqlCommand();
                 sqlcom.CommandText 
= InsertTableSql.ToString();
                 
try
                 
{
                     SqlHelper.ExecCommand(sqlcom);
                 }

                 
catch (Exception ex)
                 
{
                     
//throw ex;
                     MessageBox.Show(ex.Message);
                 }
          
                 
//DataRow row;
                 
//row=table.NewRow();
                 
//for (int i = 0; i < split[i].Length; i++)
                 
//{
                 
//    row[totalrow[i]] = split[i];
                 
                 
//}
                 
//SqlHelper.insertRow(row, "temptable", "guid");
             }

             j
++;
                
                }

                
                
//const int ERROR_FILE_NOT_FOUND = 2;
                
//const int ERROR_ACCESS_DENIED = 5;

                
//Process myproc = new System.Diagnostics.Process();
                
//myproc.StartInfo.FileName = "osql a";
                
//myproc.StartInfo.RedirectStandardError = true;
                
//myproc.StartInfo.RedirectStandardError = true;
                
//myproc.StartInfo.CreateNoWindow = true;
                
//myproc.Start();
                

 

这段程序后来遇到的问题,这当中的字段控制,如果需要要更改createtable,还有文本内容不能带单引号,以后想办法改进这个问题,工作要努力了,这个小东西都搞了两天,工作效率底下,这阶段在看net安全编程,决定对客户端/服务器端加密,预计用rsa非对称加密算法,其中会用到写数字证书.

原创粉丝点击