WebForm连接数据库实例

登录页面:用户名文本框、密码文本框、登录按钮
当用户名密码输入正确,点击确定可以跳转到下一个页面

我们需要先引入命名空间:
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;

页面代码:
           
            string name = TextBox1.Text.Trim();//获取到文本框中的用户名
            string pwd = TextBox2.Text;//获取到文本框中的密码
            //连接数据库字段
            string sqlcoon = "Data Source=.;Initial Catalog=logis;Integrated Security=True";
            string sql = string.Format("select count(*) from User1 where Account=@Account and Password=@Password_");//查询是否有该条记录,根据账户密码
            SqlParameter[] par = {
                new SqlParameter("@Account",name),
                   new SqlParameter("@Password_",pwd)
 
            };
            using (SqlConnection con = new SqlConnection(sqlcoon))//SqlConnection连接,用using释放连接
 
            {
                using (SqlCommand com = new SqlCommand(sql, con))//SqlCommand连接,用using释放连接
 
                {
                    com.Parameters.AddRange(par);
                    //打开连接
                    con.Open();
 
                    int resert = Convert.ToInt32(com.ExecuteScalar());
                    //关闭连接
                    //con.Close();
                    //释放连接
                    // con.Dispose();
                    if (resert > 0)
                    {
 
                        Response.Redirect("开票界面.aspx");
                    }
                    else
                    {
                        Label1.Text = "账户名或密码错误!";
 
                    }
                }
            } 
知识点:
1.连接数据库字段
//连接数据库字段
            string sqlcoon = "Data Source=.;Initial Catalog=logis;Integrated Security=True";
连接数据库字段是根据自己的数据库连接来写的。其中server表示运行Sql Server的计算机名,由于程序和数据库系统是位于同一台计算机的,所以我们可以用.(或localhost)取代当前的计算机名。Date Source表示所使用的数据库名(logis)。integrated security=true 的意思是集成验证,也就是说使用Windows验证的方式去连接到数据库服务器。这样方式的好处是不需要在连接字符串中编写用户名和密码,从一定程度上说提高了安全性。

2.查询语句

 string sql = string.Format("select count(*) from User1 where Account=@Account and Password=@Password_");
这样写数据库是为了防止恶意攻击数据库。

3.SqlParameter


  SqlParameter[] par = {
                new SqlParameter("@Account",name),
                   new SqlParameter("@Password_",pwd)
 
            };
SqlParameter对象在C#中获取存储过程的返回值。利用Add方法和AddRange方法来使用。
4.使用using释放资源
例如:Using(){}
using释放的是非托管资源
close()只是关闭连接,但是通道没有销毁,dispose()不仅把连接给关闭了,而且把通道也给销毁了。

可以用using来代替dispose()
5.ExecuteScalar
SqlCommand对象的三种方法:

(1)判断增删改的ExcuteNonQUery()方法,会在增删改成功之后返回数字 

(2)读取sql查询语句的内容使用SqlDataReader()方法

(3)SqlCommand.ExecuteScalar()方法的作用就是

执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他行或列,返回值为object类型

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值