SqlCommand的学习体会

  在前文使用SqlConnection连接数据库后,需要对数据库进行增、删、改、查就需要用到SqlCommand,SqlCommand主要有三个重要方法ExecuteScalar()、ExecuteNonQuery()、ExecuteReader()。

  使用步骤如下:

  一、创建SqlConnection对象(详见上文)

  二、定义SQL语句

  string sqlstr = string .Format ("select count(*) from [tb_User] where Name='{0}' and Password='{1}'",txt_Name.Text.Trim(),txt_Pwd.Text.Trim());

  注意:这里有用到string.Fomat,主要是为了格式化语句,更好定义SQL语句

  三、创建SqlCommand对象

  SqlCommand cmd = new SqlCommand(sqlstr ,conn  );

  四、调用SqlCommand的方法

  具体情况具体使用

  这里用的是

  int n=Convert .ToInt32 (cmd.ExecuteScalar());

完整代码示例

  前端程序:

  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 UserLand
{
    public partial class UserLand : Form
    {
        public UserLand()
        {
            InitializeComponent();
        }

        private void btn_Yes_Click(object sender, EventArgs e)
        {
            string connstring = "Data Source=.;Initial Catalog=AddressList;uid=sa;pwd=2wsx@WSX";
            string sqlstr = string .Format ("select count(*) from [tb_User] where Name='{0}' and Password='{1}'",txt_Name.Text.Trim(),txt_Pwd.Text.Trim());
            using (SqlConnection conn = new SqlConnection(connstring))
            {
                SqlCommand cmd = new SqlCommand(sqlstr ,conn  );
                conn.Open();
                MessageBox.Show("成功打开数据库");
                int n=Convert .ToInt32 (cmd.ExecuteScalar());
                if (n == 1)
                {
                    MessageBox.Show("用户登录成功");
                }
                else
                {
                    MessageBox.Show("用户名或密码错误");
                    txt_Name.Text  = "";
                    txt_Pwd.Text  = "";
                    txt_Name.Focus();
                }
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

  后台数据库创建代码:

IF DB_ID ('AddressList') IS NOT NULL
    DROP DATABASE AddressList ;
CREATE DATABASE AddressList
ON PRIMARY
(
    Name=AddressList,
    Filename='自己的盘符与路径\AddressList.mdf'
)
LOG ON
(
    Name=AddressList_log,
    Filename='自己的盘符与路径\AddressList_log.ldf'
)

USE AddressList ;
IF OBJECT_ID('tb_User') IS NOT NULL
    DROP TABLE tb_User;
CREATE TABLE tb_User
(
    Name varchar(20),
    Password varchar(20),
    PRIMARY KEY(Name)
)
INSERT INTO tb_User
VALUES
(
    'Admin',
    '123'
)

select * from tb_User;

  学习SqlCommand完整思路图:

 

  

posted on 2018-09-26 21:32  fenglianchen  阅读(111)  评论(0编辑  收藏  举报

导航