今天又得写一个数据库SQL Server读写的小工具,主要是涉及到一些简单的操作,没什么技术含量。
publicstatic SqlConnection conn;
staticvoid Main(string[] args)
{
ConnectionDb();
UpdateCommand();
Console.WriteLine(SelectCommand());
}
///<summary>
/// 数据库连接
///</summary>
privatestaticvoid ConnectionDb()
{
/* 介绍数据库连接的一些参数
* UID:连接数据库的用户名
* Password:连接数据库密码
* Initial Catalog:连接数据库的名称
* Data Source:数据库建的IP地址
*/
conn =new SqlConnection("UID=***;Password=***;Initial Catalog=SmokeTest;Data Source=192.168.*.*");
conn.Open();
}
///<summary>
/// 数据库查询
///</summary>
///<returns>返回查询结果</returns>
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;
}
}
staticvoid Main(string[] args)
{
ConnectionDb();
UpdateCommand();
Console.WriteLine(SelectCommand());
}
///<summary>
/// 数据库连接
///</summary>
privatestaticvoid ConnectionDb()
{
/* 介绍数据库连接的一些参数
* UID:连接数据库的用户名
* Password:连接数据库密码
* Initial Catalog:连接数据库的名称
* Data Source:数据库建的IP地址
*/
conn =new SqlConnection("UID=***;Password=***;Initial Catalog=SmokeTest;Data Source=192.168.*.*");
conn.Open();
}
///<summary>
/// 数据库查询
///</summary>
///<returns>返回查询结果</returns>
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;
}
}
就是简单的两个SQL语句,希望对大家有用吧!