Manchmal kann es einer SharePoint Anwendung sinnvoll sein,die Werte einer Liste mit denen einer Tabelle aus einer anderen Datenbank abzugleichen, z.B. wenn man Daten aus einer Anwendung in SharePoint replizieren möchte.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using Microsoft.SharePoint;
namespace Konsole2
{
class Program
{
static void Main(string[] args)
{
string strTable = "Tablename";
string strListname = "Listname";
string strUrl = "URL";
string strConn = "ConnectionString;";
string strSQL = "SELECT * from " + strTable ;
SqlConnection conn = new SqlConnection(strConn);
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(strSQL, conn);
rdr = cmd.ExecuteReader();
int itemid = 0;
int iUpdate = 0;
int iInsert = 0;
using (SPSite oSPSite = new SPSite(strUrl))
{
using (SPWeb oSPWeb = oSPSite.OpenWeb())
{
SPList list = oSPWeb.Lists[strListname];
Console.WriteLine("Table/List: " + list.Title);
while (rdr.Read())
{
itemid = Convert.ToInt32(rdr["ListItemId"]);
Console.WriteLine(itemid);
SPListItem spItem;
try
{
spItem = list.GetItemById(itemid);
}
catch (Exception ex)
{
spItem = null;
}
if (spItem != null)
{
spItem = list.Items.Add();
iInsert++;
}
// Update
iUpdate++;
for (int i = 0; i < rdr.FieldCount; i++)
{
try
{
spItem[spItem.Fields.GetFieldByInternalName(rdr.GetName(i)).Title] = rdr.GetValue(i);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message );
}
}
spItem.Update();
}
}
}
Console.WriteLine(iUpdate + " Updates");
Console.WriteLine(iInsert + " Inserts");
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}
}