using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace shiyan
{
class Program
{
static void Main(string[] args)
{
//Data Source指的是服务器名 Initial Catalog指的是数据库名
//如果Integrated Security为false需要指定ID和密码;否则将使用当前的Windows账户凭据进行身份验证
string strCon = @"Data Source = .\SQLEXPRESS;
Initial Catalog = TestDB;
Integrated Security = True;";
SqlConnection sqlCon = new SqlConnection(strCon); //执行连接
try
{
sqlCon.Open(); //打开连接
// string sqlStr = @"insert into JBQK(No,Name,XB,Grade,JG)" +
// "values('20122253','张晓明','nan','1204','重庆市')";
string sqlStr = @"select No,Name,Grade from JBQK";
string sltResult = "";
int i = 1;
SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlCon);
SqlDataReader reader = sqlCmd.ExecuteReader(); //获取数据
Console.WriteLine("数据如下:");
if (reader.HasRows) //判断reader对象中是否有数据
{
while (reader.Read())
{
//记录每一条记录
sltResult += "第" + i.ToString() + "记录:" + reader["No"].ToString() + reader["Name"].ToString() + reader["Grade"].ToString();
i++;
}
Console.WriteLine(sltResult);
}
}
catch (Exception e)
{
Console.WriteLine(e+"数据库连接失败");
}
sqlCon.Close(); //关闭连接
Console.WriteLine("数据库关闭成功");
Console.Read();
}
}
}
蜗牛—C#程设之DataReader对象
最新推荐文章于 2021-07-30 22:21:17 发布