Справочная информация:
Я пытаюсь добавить данные в базу данных SQL с помощью C #. В настоящее время я делаю это в моем сценарии в другом классе, поэтому я использую тот же код (код работает). Тем не менее, мой текущий класс использует кучу переработанного кода, и у меня возникают проблемы сужения, почему я не могу записать в БД. Ниже приведен код, который я использую, и он разбит до минимального кода.
Что я прошу:
Кто-нибудь, чтобы указать на какую-то глупую ошибку, которую я сделал, или идеи, где можно устранить неполадки. В настоящее время я просто смотрю на этот код и не вижу, что не так.
Заранее спасибо!
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());
}
}