您的位置:首页 > 其它

ADO.NET学习笔记(六)

2014-03-16 09:48 281 查看
(4)查找用户名及密码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data.SqlClient;

namespace 我的第一个数据库

{
class 查找数据

{
private string 查找SQL语句;

public string 查找属性

{
set

{

this.查找SQL语句 = value;

}

get

{

return this.查找SQL语句;

}
}
public void 查找方法()

{

using (SqlConnection conn = new SqlConnection(@"Data Source = .\SQLEXPRESS;AttachDBFilename = |DataDirectory|\Database1.mdf;Integrated Security = True;  User Instance =True"))//实现了IDisposable接口,用using括起,便于自动释放,在using()后调用了IDisposabl方法,它先判断有无conn.Close();如果没有,先进行关闭,在释放

{
conn.Open();

using (SqlCommand cmd = conn.CreateCommand())//创建命令对象的实例并与先建的数据库建立连接,将连接using进来,使此方法直接不用释放,出了括号会自动释放

{

//cmd.CommandText = "insert into MyTable1(Name)  values('杨六')";//commmandText方法是SqlCommand类的一个方法,输入要执行的SQL命令行参数

cmd.CommandText = this.查找属性;

using (SqlDataReader reader = cmd.ExecuteReader())

{

while (reader.Read()) //只能逐字向前处理,无法回头,无法往前跳着走

{

//Console.WriteLine(reader.GetString(1));//1表示读第一列(UserName的一列)

string username = reader.GetString(reader.GetOrdinal("UserName"));//GetOrdinal方法返回UserName字段的列号,有时不固定,不一定在第一列

int id = reader.GetInt32(reader.GetOrdinal("ID"));

string password = reader.GetString(reader.GetOrdinal("Password"));

Console.WriteLine("ID= {0},UserName = {1},password = {2}",id,username,password);

}

}

//cmd.ExecuteNonQuery();//执行上面的非查询语句

Console.WriteLine("查找成功!");

}

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ADO.NET class