ADO.NET基础(二)

执行查询:

一、ExecuteScalar

SqlCommand的ExecuteScalar方法用于执行查询,并返回查询所返回的结果集中第一行的第一列,因为不能确定返回值的类型,所以返回值是Object类型。

通常select count(*) from XXX使用的较多。

INSERT INTO [User]
                      (name, pass)
OUTPUT    inserted.id
VALUES     ('444', '888')

可以输出刚才插入数据的id标志值。

 二、ExecuteReader

执行有多行结果集的用ExecuteReader

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace 第三个mdf
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True"))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                   cmd.CommandText = "select * from [User]";
                    using (SqlDataReader reader = cmd.ExecuteReader()) 
                    {
                        while (reader.Read())
                        {
                            int id = reader.GetInt32(reader.GetOrdinal("id"));
                            string name = reader.GetString(reader.GetOrdinal("name"));
                            string pass = reader.GetString(reader.GetOrdinal("pass"));
                            Console.WriteLine("id={0},name={1},pass={2}",id,name,pass);
                        }
                    }
                }
                Console.ReadKey();
            }
        }
    }
}
      

ADO.NET基础(二)_第1张图片

ADO.NET基础(二)_第2张图片



 

你可能感兴趣的:(String,Security,user,database,insert,output)