2007-11-06

三种操作数据库的途径

来源: 本站收集整理 作者: 评论 0 条
 

  操作数据库可以分这么三种,第一种,直接写硬SQL代码,不要参数,第二种,直接写硬代码,要参数,第三种,调用存储过程。

  我们以一个登录模块为例,现在页面有两文本框,一按纽,实现验证用户名密码的功能。第一种方法主要代码如下:

SqlConnection conn =new SqlConnection

("server=;database=news2;uid=sa;pwd=");
conn.Open();
SqlCommand cmd=new SqlCommand();
cmd.CommandText="select count(*)from users

where name='" this.TextBox1.Text "'and pwd='" this.TextBox2.Text "'";
cmd.Connection=conn;
int i=(int)cmd.ExecuteScalar();
Response.Write(i.ToString());

if(i==1)

{

Response.Redirect("add.aspx");}

else

{

Label1.Text="error!"

}

  第二种途径  

SqlConnection conn =new SqlConnection("server=;database=news;uid=sa;pwd=");
conn.Open();//打开数据库
SqlCommand cmd=new SqlCommand();//建立命令对象
cmd.CommandText="select count(*)from users where name=@name and pwd=@pwd";
cmd.Connection=conn;//设置连接
SqlParameter p= new SqlParameter("@name",SqlDbType.Char,10);
//定义参数
p.Value=this.TextBox1.Text;
cmd.Parameters.Add(p);//添加参数到集合
p= new SqlParameter("@pwd",SqlDbType.Char,10);
p.Value=this.TextBox2.Text;
cmd.Parameters.Add(p);
int i=(int)cmd.ExecuteScalar();
if(i==1)
{
Response.Redirect("add.aspx");}
else
{
Label1.Text="error!"
}

  第三种途径


(本文仅表明作者个人观点,不代表本站及其管理员立场.) 推荐 收藏 投稿 打印 返回 关闭
上一篇:如何解决SQL Server警报的疑难问题  
下一篇:你究竟对SQL Server 2005了解多少?
    评论加载中…
SqlConnection conn =new SqlConnection("server=;database=news;uid=sa;pwd=");
conn.Open();//打开数据库
SqlCommand cmd=new SqlCommand();//建立命令对象
cmd.CommandText=" checkLogin";//设置命令文本
cmd.CommandType=CommandType.StoredProcedure;
//设置文本类型
cmd.Connection=conn;//设置连接
SqlParameter p= new SqlParameter("@name",SqlDbType.Char,10);
//定义参数
p.Value=this.TextBox1.Text;
cmd.Parameters.Add(p);//添加参数到集合
p= new SqlParameter("@pwd",SqlDbType.Char,10);
p.Value=this.TextBox2.Text;
cmd.Parameters.Add(p);
int i=(int)cmd.ExecuteScalar();
if(i==1)
{
Response.Redirect("add.aspx");}
else
{
Label1.Text="error!"
}
共2页: 上一页 1 [2] 下一页
 推荐文章
     

网站首页  -  网站地图 -   站长论坛  -  网站投稿  -    -  网站管理
Copyright © 2008 芜湖站长站 All Rights Reserved 皖ICP备07500611号