第一步:
添加引用:Microsoft.SqlServer.ConnectionInfo
using Microsoft.SqlServer.Management.Trace;
using Microsoft.SqlServer.Management.Common;
第二步:using Microsoft.SqlServer.Management.Common;
配置连接信息
ConnectionInfoBase conninfo = new SqlConnectionInfo();
((SqlConnectionInfo)conninfo).ServerName = "ServerName";
((SqlConnectionInfo)conninfo).UserName = "UserName";
((SqlConnectionInfo)conninfo).Password = "Password";
((SqlConnectionInfo)conninfo).UseIntegratedSecurity = false;
第三步:((SqlConnectionInfo)conninfo).ServerName = "ServerName";
((SqlConnectionInfo)conninfo).UserName = "UserName";
((SqlConnectionInfo)conninfo).Password = "Password";
((SqlConnectionInfo)conninfo).UseIntegratedSecurity = false;
创建mytdf.tdf文件,放入运行程序所在的文件夹里。
注:.tdf文件是用来在后面做为读取数据的模版用的,你可以在SQL Server Profiler里创建模版自己创建一个新的文件。
读取信息(包括T-SQL语句等等,按需要添加,这里只添加获取正在执行的T-SQL语句功能)
TraceServer trace = new TraceServer();
trace.InitializeAsReader(conninfo, "mytdf.tdf");
while (trace.Read())
{
//Statements;
Console.WriteLine(trace["TextData"]);
}
Console.Read();
trace.Close();
全部代码:trace.InitializeAsReader(conninfo, "mytdf.tdf");
while (trace.Read())
{
//Statements;
Console.WriteLine(trace["TextData"]);
}
Console.Read();
trace.Close();
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Trace;
using Microsoft.SqlServer.Management.Common;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
ConnectionInfoBase conninfo = new SqlConnectionInfo();
((SqlConnectionInfo)conninfo).ServerName = "ServerName";
((SqlConnectionInfo)conninfo).UserName = "UserName";
((SqlConnectionInfo)conninfo).Password = "Password";
((SqlConnectionInfo)conninfo).UseIntegratedSecurity = false;
TraceServer trace = new TraceServer();
trace.InitializeAsReader(conninfo, "mytdf.tdf");
while (trace.Read())
{
//Statements;
Console.WriteLine(trace["TextData"]);
}
Console.Read();
trace.Close();
}
}
}