VS2008连接SQLServer 2005注意点

来源:互联网 发布:win7服务优化批处理 编辑:程序博客网 时间:2024/06/06 17:04

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WinForm之登录框
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btLogin_Click(object sender, EventArgs e)
        {
            string strName = txtName.Text;
            string strPSW = txtPassword.Text;

            SqlConnectionStringBuilder strBuilder = new SqlConnectionStringBuilder();
           
            strBuilder.DataSource = @".\SQLEXPRESS";
            strBuilder.InitialCatalog="mydb";   //数据库名称
            strBuilder.UserID="sa";
            strBuilder.Password="123456";

            //连接字符串
            using (SqlConnection conn = new SqlConnection(strBuilder.ConnectionString))
            {
                conn.Open();
                //获取命令句柄
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select * from T_User where Name='" + strName + "'";
                    //执行,得到SqlDataReader对象
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            string strDBPSW = reader.GetString(reader.GetOrdinal("Password"));
                            if (strPSW == strDBPSW)
                            {
                                MessageBox.Show("登录成功");
                            }
                            else
                            {
                                MessageBox.Show("密码错误");
                            }
                        }
                        else
                        {
                            MessageBox.Show("用户名不存在");
                        }
                    }
                }
            }
        }
    }
}