支持通过ASP.NET+SQL Express保存到本地数据库[教程]

配置

这是配置应用程序的地方,您需要使用自己独特的提要和数据库设置:

使用制度;
使用System.Collections.Generic;
使用来;
使用系统文本;
使用System.Data.SqlClient;
使用SampleClientLibrary;

名称空间SampleDatabaseCreatorAndUpdater
{
班级计划
{
#区域馈送配置
private const string APIKey = "";//将API键插入变量
private const string baseUrl=”“;//将baseUrl插入变量
#端区

#区域数据库配置
私有常量字符串dbHost=“localhost\\SQLEXPRESS”;
私有常量字符串dbName=“DBSimple”;
私有常量字符串dbUser=“dnApp”;
private const string dbPass = "ppAnd";
private const string dbTableName=“newarticles”;
私有常量字符串dbTableIdentifier=“[”+dbName+”].[dbo].“+dbTableName+”];

私有静态字符串dbConnectionString=“数据源=“+dbHost”+
“用户Id=“+dbUser+”;密码=“+dbPass+”;
私有静态SqlConnection dbConnection=newsqlconnection(dbConnectionString);
#端区

[跳到顶端]

主要方法

这是执行应用程序的主线程,从这里我们检查数据库名是否已经在SQL Server上存在,如果不运行创建数据库方法。接下来,我们使用示例API返回提要的新闻项集合,并将它们传递给update数据库方法。

static void Main(string[] args)
{
dbConnection.Open();

//检查数据库是否存在
string query = "SELECT * from master.dbo.sysdatabases WHERE name=' '" + dbName + "'";
bool databaseExists=(新的SqlCommand{CommandText=query,Connection=dbConnection}.ExecuteScalar()==null)?假:真;

//仅在数据库不存在时创建数据库
如果(! databaseExists)
{
createDatabase();
}

ApiContext ac = new ApiContext(APIKey, baseUrl);//使用Api_Key创建一个新的feed对象
IEnumerablenewsList=ac.新闻//以HTML格式从提要返回最新新闻项的数组

更新数据库(新闻列表)//将新闻项目更新到数据库

dbConnection.Close()//关闭数据库连接

Console.WriteLine(“操作完成\n按任意键继续…”);
Console.ReadKey();
}

[跳到顶端]

数据库初始化

如果指定的数据库名称不存在,则执行此方法,并创建所需的news articles表。

///


///创建数据库和所需的表
///


私有静态void createDatabase()
{
/ /创建数据库
string query = "CREATE DATABASE " + dbName; / /创建数据库
SqlCommand dbCommand=新的SqlCommand(查询、dbConnection);

dbCommand.ExecuteOnQuery();

//在数据库中创建新闻文章表
dbCommand.CommandText=“创建表”+dbTableIdentifier+”(“+
"[id] int NOT NULL," +
[headline]varchar(255)不为空+
[文本]文本不为空+
[publishedDate]日期时间不为空+
[photoURL]文本为空+
“主键([id]);”;
添加(新的SqlParameter(“@dbTableName”,dbTableName));

dbCommand.ExecuteOnQuery();
}

[跳到顶端]

数据库更新

updatedatabase方法接收一个newsList对象集合,只有在数据库中不存在尊重id时才将它们持久化到数据库中。参数用于确保为查询字符串转义所有不安全字符。

///


///数据库更新方法,获取一个newsItem列表,并将每个newsItem插入到
///数据库,条件是它不存在
///


私有静态void updateDatabase(IEnumerablenewsList)
{
foreach (newsItem n in newsList)
{
SqlCommand-dbCommand=newsqlcommand{Connection=dbConnection};

添加(新的SqlParameter(“@id”,n.id));
添加(新的SqlParameter(“@headline”,n.headline));
添加(新的SqlParameter(“@text”,n.text));
dbCommand.Parameters。添加(新SqlParameter(“@publishDate”,n.publishDate));

//选择默认照片并返回largeURL
对象photoURL=DBNull.Value;
photo新闻照片= n.照片。firstordefault ();
如果(新闻照片!=null)
{
photo.Instance largePhoto=newsPhotos.Instances.Where(x=>x.type==enumeratedTypes.enumPhotoInstanceType.Large).FirstOrDefault();
if (largePhoto != null) phototourl = largePhoto.url;
}
添加(新的SqlParameter(“@photoURL”,photoURL));

//将项目插入数据库,但如果它已经存在,则忽略它
string query=“如果不存在(从“+dbTableIdentifier+”中选择*,其中id=@id)”+
“插入”+dbTableIdentifier+
“值(@id、@headline、@text、@publishDate、@photoURL)”;
dbCommand.CommandText=查询;
dbCommand.ExecuteOnQuery();
}
}
}
}

[跳到顶端]