2012年12月4日 星期二 天气阴
知道了如何连接数据库,那么现在我们怎样操作数据库呢?
可以使用ADO.NET命令对象Command来进行,下面代码是执行一条简单的查询命令:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace Command
{
class Program
{
static void Main(string[] args)
{
//连接到数据库
string theConnectionString = @"Server=(local)\SQLExpress;Database=Books Management System Datebase;Integrated Security=SSPI";
SqlConnection theConnection=new SqlConnection(theConnectionString);
theConnection.Open();
if (theConnection.State == ConnectionState.Open)
{
Console.WriteLine("数据库连接成功!");
SqlCommand theCommand = new SqlCommand();//创建一个SqlCommand实例:theCommand
theCommand.Connection = theConnection;//设置theCommand的连接
theCommand.CommandText = "select * from Member_Grade;";//设置theCommand需要执行的命令
theCommand.CommandType = CommandType.Text;//设置theCommand.CommandText的类型,text表示SQL文本命令
SqlDataReader theResult = theCommand.ExecuteReader();//ExecuteReader法方执行命令并将结果返回给theResult,类型为SqlDataReader
//显示查询结果
Console.WriteLine("会员等级编号"+"".PadLeft(8) + "会员等级"+"".PadLeft(12) + "借阅册书");
while (theResult.Read())
{
for (int i = 0; i < theResult.FieldCount; i++)
{
if (i == 0)
{
Console.Write(theResult[i] + "".PadLeft(19));
}
if (i == 1)
{
Console.Write(theResult[i] + "".PadLeft(12));
}
if (i == 2)
{
Console.Write(theResult[i]);
}
}
Console.WriteLine();
}
}
}
}
}