Is there any code sample to read the external SQL table data and create a list in SharePoint 2013, thanks in advance
1 Answer
It's a simple example via c# SSOM to retrieve Records from SQLdatabase table to existing SharePoint list
1. Create a function to get your data from SQL server and return it to a data table.
// your method to pull data from database to datatable
public DataTable GetDatafromSQL()
{
DataTable dataTable = new DataTable();
string connString = @"your connection string here";
string query = "select * from table";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
conn.Close();
da.Dispose();
return dataTable;
}
2. Create a function that loop for every item at the retrieved SQL data table and adds it to list.
void binditems()
{
DataTable dt = new DataTable();
dt= GetDatafromSQL();
using (SPSite oSite=new SPSite("http://mysharepoint"))
{
using (SPWeb oWeb=oSite.RootWeb)
{
SPList oList = oWeb.Lists["Test"];
foreach (DataRow row in dt.Rows) // Loop over the rows.
{
SPListItem oSPListItem = oList.Items.Add();
oSPListItem["Title"] = row["Title"].ToString();
oSPListItem.Update();
}
}
}
}
Read the Function binditems(), to can bind the data from SQL to List
Note : don't forget to include this namespaces using System.Data.SqlClient; using Microsoft.SharePoint;
-
Hi Qassas, Connection string throws null reference. How to add sql connection string to SharePoint webconfig fileSam Timothy– Sam Timothy2016-11-10 09:59:59 +00:00Commented Nov 10, 2016 at 9:59
-
Hi @samdaniel should you share wha't is your provided connection string line ? for add sql connection string to SP web.config check this blogs.technet.microsoft.com/msjimblog/2012/07/31/…2016-11-10 10:18:28 +00:00Commented Nov 10, 2016 at 10:18
-
@Qassas The name 'dr["Title"]' does not exit in current context. How to fix this? thanks in advanceSam Timothy– Sam Timothy2016-11-10 11:02:40 +00:00Commented Nov 10, 2016 at 11:02
-
@samdaniel replace it with row to be row["Title"].ToString(); please don't hesitate to tell me if you need any clarification or face another issue2016-11-10 11:05:24 +00:00Commented Nov 10, 2016 at 11:05