当前位置: 首页 > 编程语言 > C#

select语句的返回值共享

时间:2023-04-10 18:28:19 C#

select语句的返回值我有这个小问题。我想将select语句的结果值检索到字符串变量中。像这样OleDbCommandcmd1=newOleDbCommand();cmd1.Connection=GetConnection();cmd1.CommandText="SELECTtreatmentFROMappointmentWHEREpatientid="+text;cmd1.ExecuteNonQuery();我希望将选定的处理值放入字符串变量中。我怎样才能做到这一点。感谢您使用ExecuteReader()而不是ExecuteNonQuery()。ExecuteNonQuery()仅返回受影响的行数。尝试{SqlDataReaderdr=cmd1.ExecuteReader();}catch(SqlExceptionoError){}while(dr.Read()){字符串处理=dr[0].ToString();或者更好的是,使用using语句。using(SqlDataReaderdr=cmd1.ExecuteReader()){while(dr.Read()){字符串处理=dr[0].ToString();但是如果你的SqlCommand只返回1列,你可以使用ExecuteScalar()方法。它返回第一行的第一列,如下所示:-cmd.CommandText="SELECTtreatmentFROMappointmentWHEREpatientid="+text;字符串str=Convert.ToString(cmd.ExecuteScalar());您还可以打开SQL注入代码。始终使用参数化查询。Jeff有一篇很酷的博客文章,名为ParameterizedSQLforme,ordieforme。请仔细阅读。另请阅读DotNetPerlSqlParameter一文。当您处理查询时,SQL注入非常重要。执行标量:从数据库方法获取单个值以从数据库中检索单个值(例如,聚合值)。cmd1.Connection=GetConnection();cmd1.CommandText="SELECTtreatmentFROMappointmentWHEREpatientid="+text;如果(cmd.ExecuteScalar()==null){vartreatment=cmd.ExecuteScalar();}其他方式:ExecuteReader()try{cmd1.CommandText="SELECTtreatmentFROMappointmentWHEREpatientid=@patientID";cmd1.Parameters.AddWithValue("@patientID",this.DropDownList1.SelectedValue);conn.Open();SqlDataReaderdr=cmd1.ExecuteReader();while(dr.Read()){intPatientID=int.Parse(dr["treatment"]);}reader.Close();((IDisposable)reader).Dispose();//总是进行适当清理的好主意}catch(Exceptionexc){Response.Write(exc.ToString());}答案:Stringres=cmd1.ExecuteScalar();注意:使用参数化查询来防止sql注入你只需要使用command的ExecuteScalar方法——这会给你结果集的第一行和第一列的值。OleDbCommandcmd1=newOleDbCommand();cmd1.Connection=GetConnection();cmd1.CommandText="SELECTtreatmentFROMappointmentWHEREpatientid="+text;varresult=cmd1.ExecuteScalar();如果您的SQL语句返回多行/多列,您可以使用ExecuteReader()。您需要使用OleDbAdapter。stringconnection="你的连接";stringquery="SELECTtreatmentFROMappointmentWHEREpatientid="+text;OleDbConnectionconn=newOleDbConnection(连接);OleDbDataAdapter适配器=newOleDbDataAdapter();adapter.SelectCommand=newOleDbCommandnquery,con);适配器。填充(数据集);您的示例代码有很多问题。你有内联SQL,这在很大程度上打开了SQL注入的大门。您正在使用ExecuteNonQuery()这意味着您无法获取任何数据。以上就是C#学习教程的全部内容:select语句的返回值。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注—stringsSQL="SELECTtreatmentFROMappointmentWHEREpatientid=@patientId";OleDbCommandcmd1=newOleDbCommand(sSQL,GetConnection());//根据`GetConnectionReturns`的不同,这可能会略有不同,只需将连接字符串放在第二个参数中即可。cmd1.Parameters.AddWithValue("@patientId",text);SqlDataReaderreader=cmd1.ExecuteReader();字符串返回值;while(reader.Read()){returnValue=reader[0].ToString();}SqlConnectiondbConnect=newSqlConnection("你的SQL连接字符串");字符串名称="'项目名称'";stringstrPrj="Selecte.type,(e.surname+''+e.name)asfullnfromdbo.tblEmployeeswhereid_prj="+name;SqlCommandsqlcmd=newSqlCommand(strPrj,dbConnect);SqlDataAdaptersda=newSqlDataAdapter(strPrj,dbConnect);ds=新数据集();sda。填充(ds);数据库连接。打开();sql命令。执行非查询();数据库连接。关闭();本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: