简单的SQL Server数据库数据读取与数据操作

网络整理 - 07-27

简单实用的数据读取,数据操作方法,贴到程序里面直接调用

读取方法:


publicDataSetQuery(stringSQLText)
{
SqlConnectionmyConnection=newSqlConnection(ConfigurationSettings.AppSettings["conn"]);
DataSetds=newDataSet();
SqlDataAdaptermyCommand=newSqlDataAdapter(SQLText,myConnection);
myCommand.Fill(ds);
returnds;
}

操作方法:


//执行查询,返回SqlDataReader
publicSqlDataReaderQueryByReader(stringsqlstr)
{
if(sqlstr==String.Empty)
returnnull;

SqlConnectionmyConnection=newSqlConnection(ConfigurationSettings.AppSettings["connstring"]);
SqlCommandmyCommand=newSqlCommand(sqlstr,myConnection);

myConnection.Open();
SqlDataReaderresult=myCommand.ExecuteReader(CommandBehavior.CloseConnection);

returnresult;
}

//操作数据库,不返回结果
publicboolOperateDB(stringsqlstr)
{
if(sqlstr==String.Empty)
returnfalse;

SqlConnectionmyConnection=newSqlConnection(ConfigurationSettings.AppSettings["connstring"]);
SqlCommandmyCommand=newSqlCommand(sqlstr,myConnection);

myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();

returntrue;
}