C#数据库SQLServer查询、修改数据

今天又得写一个数据库SQL Server读写的小工具,主要是涉及到一些简单的操作,没什么技术含量。

public static SqlConnection conn;

static void Main( string [] args)
{
ConnectionDb();

UpdateCommand();
Console.WriteLine(SelectCommand());
}

///
/// 数据库连接
///

private static void ConnectionDb()
{
/* 介绍数据库连接的一些参数
* UID:连接数据库的用户名
* Password:连接数据库密码
* Initial Catalog:连接数据库的名称
* Data Source:数据库建的IP地址
*/
conn
= new SqlConnection( " UID=***;Password=***;Initial Catalog=SmokeTest;Data Source=192.168.*.* " );
conn.Open();
}

///
/// 数据库查询
///

/// 返回查询结果
private static string 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;
}
}

private static bool 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();
return true ;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false ;
}
}
就是简单的两个SQL语句,希望对大家有用吧!

转载于:https://www.cnblogs.com/Martin_Q/archive/2011/03/30/1999950.html

你可能感兴趣的:(C#数据库SQLServer查询、修改数据)