1.实现对数据库连接
publicstatic SqlConnection conn;staticvoid Main(string[] args){ConnectionDb();UpdateCommand();Console.WriteLine(SelectCommand());}// 数据库连接///privatestaticvoid ConnectionDb(){/* 介绍数据库连接的一些参数* UID:连接数据库的用户名* Password:连接数据库密码* Initial Catalog:连接数据库的名称* Data Source:数据库建的IP地址*/conn =new SqlConnection("UID=***;Password=***;Initial Catalog=SmokeTest;Data Source=192.168.*.*");conn.Open();}2.对数据进行查询访问
// 数据库查询//返回查询结果privatestaticstring SelectCommand(){var strCmd ="SELECT [Ip],[IsWatch] FROM [SmokeTest].[dbo].[Machine]"+"Where [IP]=\'192.168.*.*\'";try{SqlCommand sqlComm =new SqlCommand();sqlComm.Connection = conn;sqlComm.CommandText = strCmd;var abc = sqlComm.ExecuteNonQuery();if (abc !=-1){return"";}SqlDataReader dataReader = sqlComm.ExecuteReader();while (dataReader.Read()){return"机器IP:"+ dataReader["IP"] +"\t"+"监控状态:"+ dataReader["IsWatch"];}return"老大,没找到对应的IP喔!";}catch (Exception ex){Console.WriteLine(ex.Message);return"相当杯具啊,获取机器状态出异常了。"+ ex.Message;}}privatestaticbool UpdateCommand(){string strCmd ="update [SmokeTest].[dbo].[Machine]"+"set [IsWatch] = \'1\'"+"where IP = \'192.168.*.*\'";try{SqlCommand sqlComm =new SqlCommand();sqlComm.Connection = conn;sqlComm.CommandText = strCmd;sqlComm.ExecuteNonQuery();returntrue;}catch (Exception ex){Console.WriteLine(ex.Message);returnfalse;}}
取消
评论