欢迎访问 生活随笔!

凯发ag旗舰厅登录网址下载

当前位置: 凯发ag旗舰厅登录网址下载 > 运维知识 > 数据库 >内容正文

数据库

mysqldatareader获取整行数据给datarow-凯发ag旗舰厅登录网址下载

发布时间:2024/10/14 数据库 30 豆豆
凯发ag旗舰厅登录网址下载 收集整理的这篇文章主要介绍了 mysqldatareader获取整行数据给datarow_sqldatareader的用法(读取1整行) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

datareader对象提供只读单向数据的快速传递,单向:您只能依次读取下一条数据;只读:datareader中的数据是只读的,不能修改;相对地,dataset中的数据可以任意读取和修改

01.using (sqlconnection connection =

02. new sqlconnection(connectionstring))

03.{

04. sqlcommand command =

05. new sqlcommand(querystring, connection);

06. connection.open();

07.

08. sqldatareader reader = command.executereader();

09.

10. // 判断数据是否读到尾.

11. while (reader.read())

12. {

13. console.writeline(string.format("{0}, {1}",

14. reader[0], reader[1]));

15. }

16.

17. // 一定要关闭 reader 对象.

18. reader.close();

19.}

sqldatareader对象getordinal()方法可以查看序列号的值

01.sqlcommand cmd = new sqlcommand();

02.//存储过程应用

03.cmd.connection = conn;

04.cmd.commandtype = commandtype.storedprocedure;

05.cmd.commandtext = "listtable";

06.cmd.parameters.addwithvalue("@filename", "clsname, sort");

07.cmd.parameters.addwithvalue("@tablename", "class");

08.cmd.parameters.addwithvalue("@sort", null);

09.cmd.parameters.addwithvalue("@wherestr", "id < 10");

10.cmd.parameters.addwithvalue("@groupstr", null);

11.sqldatareader rdr = cmd.executereader();

12.int intclsname = rdr.getordinal("clsname");

13.int intsort = rdr.getordinal("sort");

14.

15.while (rdr.read())

16.{

17. console.writeline("clsname : {0}, sort:{1}", rdr[intclsname], rdr[intsort]);

18. //可以调用sqldatareader 的 get 方法来避免由于装箱,拆箱而导致的性能损失

19. console.writeline("clsname : {0}, sort:{1}", rdr.getstring(intclsname), rdr.getint32(intsort));

20. //调用sqldatareader 的 get 方法在碰到 null 值时将会产生一个 sqlnullvalueexception.可以使用isdbnull方法判断

21. articleclass arc = new articleclass();

22. arc.clsname = rdr[0];

23. if (rdr.isdbnull(rdr[1]))

24. arc.sort = null;

25. else

26. arc.sort = rdr[1];

27. arc.clsname = rdr[1];

28. arc.add(arc);

29.}

30.rdr.close();

c# 数据库使用sqlcommand进行增,删,改,查询操作

using system;

using system.collections.generic;

using system.text;

// we will make use of the sql server

// provider, however it would also be

// permissible to make use of the ado.net

// factory pattern for greater flexibility.

using system.data;

using system.data.sqlclient;

namespace autolotconnectedlayer

{

public class inventorydal

{

#region connection and disconnection details.

// this member will be used by all methods.

private sqlconnection sqlcn = new sqlconnection();

public void openconnection(string connectionstring)

{

sqlcn.connectionstring = connectionstring;

sqlcn.open();

}

public void closeconnection()

{

sqlcn.close();

}

#endregion

#region insert logic (both versions)

//public void insertauto(int id, string color, string make, string petname)

//{

// // format and execute sql statement.

// string sql = string.format("insert into inventory"

// "(carid, make, color, petname) values"

// "('{0}', '{1}', '{2}', '{3}')", id, make, color, petname);

//

// // execute using our connection.

// using(sqlcommand cmd = new sqlcommand(sql, this.sqlcn))

// {

// cmd.executenonquery();

// }

//}

public void insertauto(int id, string color, string make, string petname)

{

// note the 'placeholders' in the sql query.

string sql = string.format("insert into inventory"

"(carid, make, color, petname) values"

"(@carid, @make, @color, @petname)");

// this command will have internal parameters.

using (sqlcommand cmd = new sqlcommand(sql, this.sqlcn))

{

// fill params collection.

sqlparameter param = new sqlparameter();

param.parametername = "@carid";

param.value = id;

param.sqldbtype = sqldbtype.int;

cmd.parameters.add(param);

param = new sqlparameter();

param.parametername = "@make";

param.value = make;

param.sqldbtype = sqldbtype.char;

param.size = 10;

cmd.parameters.add(param);

param = new sqlparameter();

param.parametername = "@color";

param.value = color;

param.sqldbtype = sqldbtype.char;

param.size = 10;

cmd.parameters.add(param);

param = new sqlparameter();

param.parametername = "@petname";

param.value = petname;

param.sqldbtype = sqldbtype.char;

param.size = 10;

cmd.parameters.add(param);

cmd.executenonquery();

}

}

#endregion

#region delete logic

public void deletecar(int id)

{

// get id of car to delete, then do so.

string sql = string.format("delete from inventory where carid = '{0}'",

id);

using (sqlcommand cmd = new sqlcommand(sql, this.sqlcn))

{

try

{

cmd.executenonquery();

}

catch (sqlexception ex)

{

exception error = new exception("sorry! that car is on order!", ex);

throw error;

}

}

}

#endregion

#region update logic

public void updatecarpetname(int id, string newpetname)

{

// get id of car to modify and new pet name.

string sql =

string.format("update inventory set petname = '{0}' where carid = '{1}'",

newpetname, id);

using (sqlcommand cmd = new sqlcommand(sql, this.sqlcn))

{

cmd.executenonquery();

}

}

#endregion

#region select logic

public datatable getallinventory()

{

// this will hold the records.

datatable inv = new datatable();

// prep command object.

string sql = "select * from inventory";

using (sqlcommand cmd = new sqlcommand(sql, this.sqlcn))

{

sqldatareader dr = cmd.executereader();

// fill the datatable with data from the reader and clean up.

inv.load(dr);

dr.close();

}

return inv;

}

#endregion

#region trigger stored proc logic

public string lookuppetname(int carid)

{

string carpetname = string.empty;

// establish name of stored proc.

using (sqlcommand cmd = new sqlcommand("getpetname", this.sqlcn))

{

cmd.commandtype = commandtype.storedprocedure;

// input param.

sqlparameter param = new sqlparameter();

param.parametername = "@carid";

param.sqldbtype = sqldbtype.int;

param.value = carid;

param.direction = parameterdirection.input;

cmd.parameters.add(param);

// output param.

param = new sqlparameter();

param.parametername = "@petname";

param.sqldbtype = sqldbtype.char;

param.size = 10;

param.direction = parameterdirection.output;

cmd.parameters.add(param);

// execute the stored proc.

cmd.executenonquery();

// return output param.

carpetname = ((string)cmd.parameters["@petname"].value).trim();

}

return carpetname;

}

#endregion

#region tx method

// a new member of the inventorydal class.

public void processcreditrisk(bool throwex, int custid)

{

// first, look up current name based on customer id.

string fname = string.empty;

string lname = string.empty;

sqlcommand cmdselect = new sqlcommand(

string.format("select * from customers where custid = {0}", custid), sqlcn);

using (sqldatareader dr = cmdselect.executereader())

{

while (dr.read())

{

fname = (string)dr["firstname"];

lname = (string)dr["lastname"];

}

}

// create command objects which represent each step of the operation.

sqlcommand cmdremove = new sqlcommand(

string.format("delete from customers where custid = {0}", custid), sqlcn);

sqlcommand cmdinsert = new sqlcommand(string.format("insert into creditrisks"

"(custid, firstname, lastname) values"

"({0}, '{1}', '{2}')", custid, fname, lname), sqlcn);

// we will get this from the connection object.

sqltransaction tx = null;

try

{

tx = sqlcn.begintransaction();

// enlist the commands into this transaction.

cmdinsert.transaction = tx;

cmdremove.transaction = tx;

// execute the commands.

cmdinsert.executenonquery();

cmdremove.executenonquery();

// simulate error.

if (throwex)

{

throw new applicationexception("sorry! database error! tx failed...");

}

// commit it!

tx.commit();

}

catch (exception ex)

{

console.writeline(ex.message);

// any error will rollback transaction.

tx.rollback();

sqlcommand 对象的 executescalar 方法返回一个 object 数据类型中第一行第一列的值。

view plaincopy to clipboardprint?

01.sqlcommand cmd = new sqlcommand();

02.//存储过程应用

03.cmd.connection = conn;

04.cmd.commandtype = commandtype.storedprocedure;

05.cmd.commandtext = "listtable";

06.cmd.parameters.addwithvalue("@filename", "top 1 id");

07.cmd.parameters.addwithvalue("@tablename", "class");

08.cmd.parameters.addwithvalue("@sort", null);

09.cmd.parameters.addwithvalue("@wherestr", "id < 4");

10.cmd.parameters.addwithvalue("@groupstr", null);

11.//可以直接使用 object obj = cmd.executescalar(); 然后判断 obj == null 并进行下步操作

12.int classid = (int)cmd.executescalar();

13.console.writeline(classid);

executenonquery执行不返回结果集的查询,sqlcommand 对象的 executenonquery 方法

view plaincopy to clipboardprint?

01.string update_sp = "update class set clsname = @classname where id = @classid";

02.sqlcommand cmd = new sqlcommand(update_sp, conn);

03.sqlparameter[] p = new sqlparameter[2]{

04. new sqlparameter("@classname", dbtype.string),

05. new sqlparameter("@classid", dbtype.int32)

06.};

07.p[0].value = "ado.net";

08.p[1].value = 7;

09.

10.foreach (sqlparameter parm in p)

11. cmd.parameters.add(p);

12.

13.int executenum = cmd.executenonquery();

14.console.writeline(executenum);

parameters参数化查询

,上述代码中已经实现参数化查询。parameters 的作用可有效防止注入。利用addwithvalue 方法把参数传递给 cmd 对象。sqlparameter 对象详解

view plaincopy to clipboardprint?

01.//sqlparameter 对象,利用sqlcommand addwithvalue方法创建 同等于下面

02.cmd.parameters.addwithvalue("@classid", 3);

03.

04.//sqlparameter 对象

05.sqlparameter p = new sqlparameter("@classid", dbtype.int16);

06.p.value = 3;

07.cmd.parameters.add(p);

批量操作查询

,用statementcompleted事件获取批量操作查询时个语句返回的影响数

view plaincopy to clipboardprint?

01.static void handlestatementcompleted(object sender, statementcompletedeventargs e)

02.{

03. console.writeline("查询影响:{0} row(s)", e.recordcount);

04.}

05.//..........................................

06.string sql = "update class set num = 1 where id = 3;"

07. "update class set num = 2 where id = 4;"

08. "update class set num = 3 where id = 5;"

09. "update class set num = 4 where id = 6;";

10.sqlcommand cmd = new sqlcommand(sql, conn);

11.cmd.statementcompleted = new statementcompletedeventhandler(handlestatementcompleted);

12.int executenum = cmd.executenonquery();

13.console.writeline("批量查询共影响:{0} row(s)", executenum);

14.

15.//输出来自查询的多个结果集

16.do {

17. while (rdr.read())

18. console.writeline("{0} - {1}", rdr[0], rdr[1]);

19.

20.} while (rdr.nextresult());

执行异步查询,sqlcommand公开了begin, end方法,例如:beginexecutereader, endexecutereader方法

每个 begin 方法返回一个实现 iasyncresult 接口对象。这一返回对象是查询状态的一个句柄,iasyncresult 接口是用于异步方法的.net framework 模式的一部分,其设计目的:帮助确定该操作是否已经完成如果需要等待该操作完成则中断当前线程;用作方法调用的句柄。 iasyncresult 接口的iscompleted 属性,以查看 beginexecutereader 调用是否已经完成。调用iasyncresult.asyncwaithandle.waitone 使用iasyncresult接口来等待该调用完成 。

view plaincopy to clipboardprint?

01.using system.threading; //需引用此命名空间

02.

03.conn.open();

04.string sql = "waitfor delay '00:00:10' ;"

05. "select * from class";

06.sqlcommand cmd = new sqlcommand(sql, conn);

07.iasyncresult iar = cmd.beginexecutereader();

08.console.writeline("异步查询是否已经获取记录?");

09.while (!iar.iscompleted)

10.{

11. console.writeline("否,还在等待.");

12. iar.asyncwaithandle.waitone(1000, true);

13.}

14.console.writeline("是,已经获取数据.");

15.

16.sqldatareader rdr = cmd.endexecutereader(iar);

17.while (rdr.read())

18.{

19. console.writeline(rdr["clsname"]);

20.}

21.rdr.close();

总结

以上是凯发ag旗舰厅登录网址下载为你收集整理的mysqldatareader获取整行数据给datarow_sqldatareader的用法(读取1整行)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发ag旗舰厅登录网址下载网站内容还不错,欢迎将凯发ag旗舰厅登录网址下载推荐给好友。

网站地图