C#将数据添加到SQL数据库

时间:2011-03-03 14:18:55

标签: c# sql

背景: 我正在尝试使用C#将数据添加到SQL DB。我目前在另一个类的脚本中这样做,所以我使用相同的代码(代码工作)。但是,我目前的课程正在使用一堆回收代码,我正在解决为什么我不能写入数据库的问题。下面是我正在使用的代码,它分解为简单的最小代码。

我要求的是: 有人指出我做的一些愚蠢的错误或想法在哪里进行故障排除。目前我只是盯着这段代码而且看不出什么错误。

提前致谢!

public void AddAttachmentToDB(XmlNode root, XmlNamespaceManager xmlns, string  MessageID, string MailBoxAliasName)
{
    //open DB
    #region Open DB
    if (DbConnection.State != System.Data.ConnectionState.Open)
    {
        try
        {
            this.DbConnection.ConnectionString = DbConnectionString;
            this.DbConnection.Open();
            MailboxListener._logging.LogWrite("[{0}] opened DB Connection in AddAttachmentToDB!",
                LoggingLevels.Error,
                System.Reflection.MethodBase.GetCurrentMethod().ToString(),
                this.DbConnectionString);
        }
        catch (Exception ex)
        {
            MailboxListener._logging.LogWrite("[{0}] Failed to open DB Connection! For Machine: {1}",
                 LoggingLevels.Error,
                 System.Reflection.MethodBase.GetCurrentMethod().ToString(),
                 this.DbConnectionString);
            MailboxListener._logging.LogWrite("[{0}] Error Returned: {1}",
                LoggingLevels.Error,
                System.Reflection.MethodBase.GetCurrentMethod().ToString(),
                ex.Message.ToString());
        }
    }
    else
    {
        MailboxListener._logging.LogWrite("[{0}] Failed to open DB Connection in AddAttachmentToDB!",
                 LoggingLevels.Error,
                 System.Reflection.MethodBase.GetCurrentMethod().ToString(),
                 this.DbConnectionString);
    }
            #endregion
    //once db is open try this
    try
    {
        //create test variables       
        string strMailBoxAliasName = MailBoxAliasName;
        string AttachmentFilename = string.Empty;
        string strfiletype = string.Empty;
        string AttachmentStream = string.Empty;
        string strAttachmentID = string.Empty;
        string strMessageID = string.Empty;
        strMessageID = MessageID;

        //fill test variables
        AttachmentFilename = "yumyum";
        AttachmentStream = "Cheetos";
        strMessageID = "123";
        strMailBoxAliasName = "user";
        strfiletype = ".txt";
        strAttachmentID = "12345";

        //create sql insert string
        String insString = @"INSERT INTO MailboxListenerAttachments Values (@attachmentfilename, @attachmentbody,
        @messageID, @mailboxname, @filetype, @attachmentID, @DateAddedToDB)";

        //create sql command string
        SqlCommand myCommand = new SqlCommand(insString, this.DbConnection);

        //add fill test variables to sql insert string
        myCommand.Parameters.Add("@attachmentfilename", SqlDbType.VarChar, 100);
        myCommand.Parameters["@attachmentfilename"].Value = AttachmentFilename;
        myCommand.Parameters.Add("@attachmentbody", SqlDbType.VarChar, 8000);
        myCommand.Parameters["@attachmentbody"].Value = AttachmentStream.Trim();
        myCommand.Parameters.Add("@messageID", SqlDbType.VarChar, 500);
        myCommand.Parameters["@messageID"].Value = strMessageID;
        myCommand.Parameters.Add("@mailboxname", SqlDbType.VarChar, 100);
        myCommand.Parameters["@mailboxname"].Value = strMailBoxAliasName;
        myCommand.Parameters.Add("@filetype", SqlDbType.VarChar, 50);
        myCommand.Parameters["@filetype"].Value = strfiletype;
        myCommand.Parameters.Add("@attachmentID", SqlDbType.VarChar, 50);
        myCommand.Parameters["@attachmentID"].Value = strAttachmentID;
        myCommand.Parameters.Add("@DateAddedToDB", SqlDbType.DateTime);
            myCommand.Parameters["@DateAddedToDB"].Value = DateTime.UtcNow.ToString();

        //run sql command
        myCommand.ExecuteNonQuery();

        //log sql command events
        MailboxListener._logging.LogWrite(
                "[{0}] Added attachment {1} to database for messageID: {2}",
                LoggingLevels.Informational,
                System.Reflection.MethodBase.GetCurrentMethod().ToString(),
                AttachmentFilename,
                strMessageID
            );
        //if DB is open, close it
        if (DbConnection.State == System.Data.ConnectionState.Open)
        {
            this.DbConnection.Close();
        }
    }
    //catch errors 
    catch (Exception ex)
    {
        MailboxListener._logging.LogWrite("[{0}] Error Returned: {1}",
                LoggingLevels.Error,
                System.Reflection.MethodBase.GetCurrentMethod().ToString(),
                ex.Message.ToString());
    }
}

4 个答案:

答案 0 :(得分:3)

不知道为什么这不起作用,但这段代码为重构而尖叫:

public void AddAttachmentToDB(
    XmlNode root, 
    XmlNamespaceManager xmlns, 
    string MessageID, 
    string MailBoxAliasName
)
{
    var strMailBoxAliasName = MailBoxAliasName;
    var AttachmentFilename = "yumyum";
    var AttachmentStream = "Cheetos";
    var strMessageID = "123";
    var strMailBoxAliasName = "user";
    var strfiletype = ".txt";
    var strAttachmentID = "12345";

    // Use DateTime when working with dates
    var dates123 = new DateTime(2011, 2, 3);

    try
    {
        using (var conn = new SqlConnection(DbConnectionString))
        using (var cmd = conn.CreateCommand())
        {
            conn.Open();
            cmd.CommandText = @"INSERT INTO MailboxListenerAttachments Values (@attachmentfilename, @attachmentbody, @messageID, @mailboxname, @filetype, @attachmentID, @DateAddedToDB";

            cmd.Parameters.AddWithValue("@attachmentfilename", AttachmentFilename);
            cmd.Parameters.AddWithValue("@attachmentbody", AttachmentStream.Trim());
            cmd.Parameters.AddWithValue("@messageID", strMessageID);
            cmd.Parameters.AddWithValue("@mailboxname", strMailBoxAliasName);
            cmd.Parameters.AddWithValue("@filetype", strfiletype);
            cmd.Parameters.AddWithValue("@attachmentID", strAttachmentID);
            cmd.Parameters.AddWithValue("@DateAddedToDB", dates123);

            cmd.ExecuteNonQuery();
        }
    }
    catch (Exception ex)
    {
        // TODO: Log the exception and propagate it
        throw ex;
    }
}

答案 1 :(得分:0)

Dates123不应该是DateTime类型而不是字符串吗?

答案 2 :(得分:0)

我认为您需要为所有参数指定输入/输出方向。 例如:myCommand.Parameters["@attachmentfilename"].Direction = ParameterDirection.Input

答案 3 :(得分:0)

如果你真的不知道可以尝试

  1. 修复你的insert语句 明确地命名列可能是你的 订购不正确并插入 声明不起作用
  2. 您的设置参数长度为 最大列长度值,也许是你 需要将它们设置为实际参数 值长度
  3. 我真的认为Dates123是 确实是这里最重要的问题,它 应该是DateTime而不是字符串。
  4. 所以你改了它但你仍然调用DateTime.UtcNow.ToString(),把它留作DateTime类型而不是字符串。