首页 / C# / c# – 为新插入查看SQL表的有效方法
c# – 为新插入查看SQL表的有效方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 为新插入查看SQL表的有效方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含5511字,纯文字阅读大概需要8分钟。
内容图文
![c# – 为新插入查看SQL表的有效方法](/upload/InfoBanner/zyjiaocheng/907/4d54ff3585904e4ea37800a6cd721fda.jpg)
我有一个推送服务,将传入的数据插入到SQL表中,我需要创建一个应用程序来监听此表以查看新的传入数据.
有没有办法听这个表而不必经常选择数据库进行新的更改?如果没有使用这个数据shoud我只是在阅读后删除该行或是否更好地定期清理?
UPDATE2
这是我的实际代码,它没有给我任何插入表的通知,我做错了什么?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Navman_SPI_Service
{
public partial class Service1 : ServiceBase
{
SqlConnection con = new SqlConnection();
String passAvl = Properties.Settings.Default.AVLPass;
String usuarioAvl = Properties.Settings.Default.AVLuser.ToString();
String servidor = Properties.Settings.Default.Server.ToString();
String DataB = Properties.Settings.Default.DB.ToString();
String SQLuser = Properties.Settings.Default.DBuser.ToString();
String SQLpass = Properties.Settings.Default.DBpassword.ToString();
SqlCommand dependencyCommand = new SqlCommand();
String connectionString = "";
public Service1()
{
InitializeComponent();
}
public String getQuery()
{
return "SELECT MessageID FROM dbo.navman_ic_api_message WHERE Proccessed IS NULL";
}
public void OnDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
dependencyCommand.CommandText = getQuery();
connectionString = "Data Source=";
connectionString += servidor + ";Initial Catalog=FOO;Persist Security Info=True;User ID=";
connectionString += SQLuser + ";Password=";
connectionString += SQLpass + ";Initial Catalog=" + DataB;
con = new SqlConnection(connectionString);
try
{
con.Open();
}
catch (Exception f)
{
var logging = new StringBuilder();
var filePath = @"c:\temp\log.txt";
String timestamp = DateTime.Now.ToString("[yyyy:MM:dd][HH:mm:ss]");
logging.Append(timestamp + Environment.NewLine + Environment.NewLine + connectionString + Environment.NewLine + Environment.NewLine + f.ToString() + Environment.NewLine + Environment.NewLine);
File.AppendAllText(filePath, logging.ToString());
}
if (con.State == ConnectionState.Open)
{
Initialization();
dependencyStarter();
var logging = new StringBuilder();
var filePath = @"c:\temp\test.txt";
String timestamp = DateTime.Now.ToString("[yyyy:MM:dd][HH:mm:ss]");
logging.Append(timestamp + Environment.NewLine + Environment.NewLine + "SUCCESS" + Environment.NewLine + Environment.NewLine);
File.AppendAllText(filePath, logging.ToString());
}
}
protected override void OnStop()
{
Termination();
}
void dependencyStarter()
{
// Assume connection is an open SqlConnection.
// Create a new SqlCommand object.
using (SqlCommand command = new SqlCommand(getQuery(),con))
{
// Create a dependency and associate it with the SqlCommand.
SqlDependency dependency = new SqlDependency(dependencyCommand);
// Maintain the refence in a class member.
// Subscribe to the SqlDependency event.
dependency.OnChange += new
OnChangeEventHandler(OnDependencyChange);
// Execute the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// Process the DataReader.
}
}
}
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
// Handle the event (for example, invalidate this cache entry).
var logging = new StringBuilder();
var filePath = @"c:\temp\test.txt";
String timestamp = DateTime.Now.ToString("[yyyy:MM:dd][HH:mm:ss]");
logging.Append(timestamp + Environment.NewLine + Environment.NewLine + sender.ToString() + Environment.NewLine + Environment.NewLine);
File.AppendAllText(filePath, logging.ToString());
}
void Termination()
{
// Release the dependency.
SqlDependency.Stop(connectionString);
}
void Initialization()
{
// Create a dependency connection.
SqlDependency.Stop(connectionString);
SqlDependency.Start(connectionString);
}
}
}
谢谢,
解决方法:
尝试使用SqlDependency. Detecting Changes with SqlDependency
我在很多项目中都使用过它们,它们看起来效果很好.这使用QueryNotifications,它是SQL Server Service Broker的一部分.
如果Broker尚未激活,则必须启用它.让DBA运行如下所示的内容:
USE master;
GO
ALTER DATABASE MyDatabase SET ENABLE_BROKER;
GO
文章的示例代码:
void Initialization()
{
// Create a dependency connection.
SqlDependency.Start(connectionString, queueName);
}
void SomeMethod()
{
// Assume connection is an open SqlConnection.
// Create a new SqlCommand object.
using (SqlCommand command=new SqlCommand(
"SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers",
connection))
{
// Create a dependency and associate it with the SqlCommand.
SqlDependency dependency=new SqlDependency(command);
// Maintain the refence in a class member.
// Subscribe to the SqlDependency event.
dependency.OnChange+=new
OnChangeEventHandler(OnDependencyChange);
// Execute the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// Process the DataReader.
}
}
}
// Handler method
void OnDependencyChange(object sender,
SqlNotificationEventArgs e )
{
// Handle the event (for example, invalidate this cache entry).
}
void Termination()
{
// Release the dependency.
SqlDependency.Stop(connectionString, queueName);
}
基本上,您在SQL Server中设置一个回调,只要给定查询的结果发生变化,就会调用该回调.然后你可以自己做点什么.
您可能希望在表格上有一列,以便您可以判断数据是否为新数据.像“CreateDate”或“Processed”之类的东西.从依赖项查询中排除它.然后你可以在以后使用它来获取新的东西.
我应该注意,如果表经常更改,最好定期进行轮询,只需将所有更改作为一个批处理,而不是一次尝试处理它们. SqlDependency非常适合刷新缓存数据.处理一个用作事务队列的表并不好.
完成后我不会删除数据.只需在下一个查询中忽略它,或者将其移动到存档表.如果您以后需要对其进行故障排除,删除信息通常是一个坏主意.
内容总结
以上是互联网集市为您收集整理的c# – 为新插入查看SQL表的有效方法全部内容,希望文章能够帮你解决c# – 为新插入查看SQL表的有效方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。