在這裏我需要創建一個DataTable,但它不會返回一個id.There沒有錯誤。實際上,在這裏我提供了一個電子郵件地址(epost)。並且我需要從數據庫返回id。ID不從ExecuteNonQuery()返回;
編碼部分到這裏。
public string GetAllMails()
{
DataConnection dc = new DataConnection();
string e="";
int uid=-1,sid=0;
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("uid");
dt.Columns.Add("email");
Microsoft.Office.Interop.Outlook.Application oApp;
Microsoft.Office.Interop.Outlook._NameSpace oNS;
Microsoft.Office.Interop.Outlook.MAPIFolder oFolder;
Microsoft.Office.Interop.Outlook._Explorer oExp;
oApp = new Microsoft.Office.Interop.Outlook.Application();
oNS = (Microsoft.Office.Interop.Outlook._NameSpace)oApp.GetNamespace("MAPI");
oFolder = oNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
oExp = oFolder.GetExplorer(false);
oNS.Logon(Missing.Value, Missing.Value, false, true);
Microsoft.Office.Interop.Outlook.Items items = oFolder.Items;
SqlConnection conn = dc.SqlConnection;
if (conn.State != ConnectionState.Open) conn.Open();
SqlCommand cmd = new SqlCommand("GetDetailsByEmail", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter();
foreach (Microsoft.Office.Interop.Outlook.MailItem mail in items)
{
if (mail.UnRead == true)
{
e=mail.SenderEmailAddress;
// param <-- add sql parameters
cmd.Parameters.Add(new SqlParameter("@epost",e));
uid = cmd.ExecuteNonQuery();
//send to db and take the id (uid)
//if returned id
DataRow row = dt.NewRow();
row["id"] = sid;
sid++;
row["uid"] = uid;// uid
row["email"] = e;
dt.Rows.Add(row);
}
}
return e;
}
存儲過程放在這裏
ALTER Procedure [dbo].[GetDetailsByEmail]
@epost nvarchar(50)
AS
BEGIN
Select Medlems_ID,[E-post]
from dbo.Members
where [E-post] = @epost
END
當我編輯編碼,UID是INT。
uid = cmd.ExecuteReader(); or uid = cmd.ExecuteScalar(); // it shows me conversion error.here i put as a comment
'ExecuteNonQuery'用於INSERT,UPDATE,DELETE ...不適用於SELECT語句。使用ExecuteReader()代替 – codingbiz
如果您的查詢始終返回一個值,則可以使用['ExcecuteScalar'](http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlcommand.executescalar.aspx )。 –
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx – Techmaster