手机
当前位置:查字典教程网 >编程开发 >mssql数据库 >三种操作数据库的途径
三种操作数据库的途径
摘要:操作数据库可以分这么三种,第一种,直接写硬SQL代码,不要参数,第二种,直接写硬代码,要参数,第三种,调用存储过程。我们以一个登录模块为例,...

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

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

SqlConnection conn =new SqlConnection

("server=;database=news2;uid=sa;pwd=");

conn.Open();

SqlCommand cmd=new SqlCommand();

mandText="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();//建立命令对象

mandText="select count(*)from users where and ";

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!"

}

第三种途径

SqlConnection conn =new SqlConnection("server=;database=news;uid=sa;pwd=");

conn.Open();//打开数据库

SqlCommand cmd=new SqlCommand();//建立命令对象

mandText=" checkLogin";//设置命令文本

mandType=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!"

}

接下来对这三种方法做分析:

第一方法不能防范SQL注入式方式攻击,比如在第一个文本框输入asd'or's'='s 第二个同样输入asd'or's'='s ,可以发现成功通过验证。

第二种直接写硬SQL代码,事实上不是每个人都能写出优良的SQL代码来,可以由数据库管理员或工程师来写,这样,一方面减轻程序员的工作,另一方面也可以使数据库与应用程序保持独立,这样有利于系统的移植与维护。

当然第三种是推荐使用的,好处呢!就是前面所写的。

【三种操作数据库的途径】相关文章:

SqlServer2005 数据库同步配置图文详解

SQL2005CLR函数扩展-数据导出的实现详解

SQL查询日志 查看数据库历史查询记录的方法

SQL Server 2005恢复数据库详细图文教程

mssql server .ldf和.mdf的文件附加数据库的sql语句

SQL小技巧 又快又简单的得到你的数据库每个表的记录数

SQL字符串处理函数总结

SQL Server 2000中修改数据库COLLATE的实例

SQL Server中统计每个表行数的快速方法

SQLite数据库

精品推荐
分类导航