浅谈SqlCommand

初学asp.net 的菜鸟应该都会像我一样想尝试一下前后台的交互吧!特别是与数据库的交互。下面就来说一下自己的个人经历。

SqlCommand

首先需要引入system.Date.SqlClient命名空间

注意SqlCommand不支持DateDrict类型。

创建一个SqlCommand对象

SqlCommand cmd = new SqlCommand(); //创建对象
cmd.Connection = new SqlConnection(connect); //创建连接字符串connect 是我预先写好的连接字符串
cmd.Connection.Open();//打开连接
cmd.CommandText = "SELECT [书名], [ISBN], [出版社] FROM [BOOKINFO]";//创建sql语句
cmd.CommandType = CommandType.Text;//指明类型为Text类型

//SqlCommand不支持TableDriect
//cmd.CommandText = "BOOKINFO"; //表名
//cmd.CommandType = CommandType.TableDirect; //指明类型为表类型
//cmd.CommandText = "GetBook"; //存储过程名
//cmd.CommandType = CommandType.StoredProcedure; //指明类型为存储过程

Table T=new Table(); //用来动态接收数据

SqlDataReader re = re = cmd.ExecuteReader(); //创建SqlDataReader从返回值中读取数据(一行行的读取)
try
{
while (re.Read())
{
TableRow tr = new TableRow(); //创建行标签对象
for (int i = 0; i < re.FieldCount; i++) //FieldCount获取每行的列数
{
//Response.Write(re[i]);
TableCell td = new TableCell(); //创建列标签对象
td.Text = re[i].ToString();
tr.Cells.Add(td);
}
//Response.Write("<br/>");
t.Rows.Add(tr);
}
this.Controls.Add(t);
}
finally
{
re.Close(); //结束读取
}
cmd.Connection.Close(); //关闭连接

}

一个小例子就写完了。表里没有建样式,页面比较丑。详细的解说可以到MSDN上查阅。

 

posted on 2015-03-27 16:57  FightLi  阅读(580)  评论(2编辑  收藏  举报