Windows service with sql [closed]
partial class TestService : ServiceBase
{
FileStream fs;
StreamWriter sw;
public TestService()
{
InitializeComponent();
fs = new FileStream(@"C:\SampleLast.txt", FileMode.Create);
sw = new StreamWriter(fs);
}
protected override void OnStart(string[] args)
{
try
{
if (!File.Exists(@"C:\SampleLast.txt"))
{
fs = new FileStream(@"C:\SampleLast.txt", FileMode.Create);
sw = new StreamWriter(fs);
}
sw.WriteLine("Service start {0}", DateTime.Now.ToString());
Timer timerNew = new Timer();
timerNew.Elapsed += new ElapsedEventHandler(timerNew_Elapsed);
timerNew.Enabled = true;
timerNew.Interval = 4000;
timerNew.Start();
sw.WriteLine(timerNew.Enabled.ToString());
sw.Flush();
}
catch(Exception Ex)
{
sw.WriteLine(Ex.ToString());
sw.Flush();
}
}
void timerNew_Elapsed(object sender, ElapsedEventArgs e)
{
sw.WriteLine("timer is working...{0}", DateTime.Now.ToString());
SqlConnection conn;
SqlCommand comm;
conn = new SqlConnection(@"Data Source=.;Initial Catalog=MailDB;Integrated Security=True");
comm = new SqlCommand("select Text,product from Source", conn);
conn.open();
SqlDataReader rd = comm.ExecuteReader();
while (rd.Read())
{
if (Convert.ToInt32(rd["Text"]) < 20)
{
sw.WriteLine("{0} stock state {1}", rd["product"].ToString(), rd["stock"].ToString());
}
}
sw.Flush();
}
protected override void OnStop()
{
}
}
I want to use Windows service for my project. When I use those codes I don't have any problems.
Problem is when I add some SQL code in timer blocks. I have some effect in SampleLast.text file. Just running codes where OnStart()
methods. I can't understand what is problem.Problem is when i use sqllconnection and sqlcommand codes, timer dosent work.
conn = new SqlConnection(@"Data Source=.;Initial Catalog=MailDB;Integrated Security=True");
comm = new SqlCommand("select Text,product from Source", conn);
SqlDataReader rd = comm.ExecuteReader();
You don't mention what your problem is, but you are never actually opening your SQL connection, so this should never have worked.
I'd recommend refactoring and using using
blocks:
using(SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=MailDB;Integrated Security=True"))
using (SqlCommand comm = new SqlCommand("select Text,product from Source", conn))
{
conn.Open();
using (SqlDataReader rd = comm.ExecuteReader())
{
//...
}
}
精彩评论