书上又有一个错误,我的数据库结构式这样的:
CREATE TABLE [dbo].[Student](
[Sno] [char](5) COLLATE Chinese_PRC_CI_AS NOT NULL,
[Sname] [varchar](8) COLLATE Chinese_PRC_CI_AS NULL,
[Ssex] [bit] NULL,
[Sbirth] [smalldatetime] NULL,
[Sdept] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
[BirthPlace] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[Spay] [smallmoney] NULL,
PRIMARY KEY CLUSTERED
(
[Sno] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY],
CONSTRAINT [SUDENT_UQ] UNIQUE NONCLUSTERED
(
[Sname] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
上面有点乱,因为数据库是我很久以前建的,我只好复制粘贴系统生成的代码了,很好写的
打开VS创建一个C#windows console application
代码如下
using System;
using System.Data;
using System.Data.SqlClient;
namespace sql1._2
{
class Program
{
static string ConnectionString = @"Data Source=(local);Initial Catalog=MY_DBMS;Integrated Security=True";
static void Main(string[] args)
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Student", con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) //这里书上写的是reader.Read,这是一个集合,不是一行,报错
{
string sno = reader.GetString(0); //0表示第一个字段
string sname = reader.GetString(1); //1表示第二个字段
Boolean ssex = reader.GetBoolean(2);
DateTime date = reader.GetDateTime(3);
string sdept = reader.GetString(4);
if (ssex == true)
{
Console.WriteLine(sno + " " + sname +" "+ "男" +" "+ date+" " + sdept);
}
else
{
Console.WriteLine(sno + " " + sname + " " + "女" + " " + date + " " + sdept);
}
}
}
catch(Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}
}