本文共 2270 字,大约阅读时间需要 7 分钟。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data;//必须引入using System.Data.SqlClient;//必须引入namespace Command{ class Program { static void Main(string[] args) { //构造连接字符串 SqlConnectionStringBuilder strConn = new SqlConnectionStringBuilder(); strConn.DataSource =@"你的数据库服务器"; strConn.InitialCatalog = "你要连得数据库名"; strConn.IntegratedSecurity = true; using (SqlConnection conn = new SqlConnection(strConn.ConnectionString)) { string strSQL = "select Top 1 * From dbo.Course_1_Name"; SqlCommand cmd = new SqlCommand(strSQL, conn);//使用构造函数方式创建Command对象 conn.Open();//记得打开连接try { SqlDataReader reader = cmd.ExecuteReader();//执行ExecuteReader if (reader != null && reader.HasRows) { int rows = 0;//记录行数 Console.WriteLine("**********Highest Score of Course_1**********\n"); while (reader.Read()) { for (int i = 0; i < reader.FieldCount; ++i) { Console.WriteLine("{0}:{1}", reader.GetName(i), reader.GetValue(i)); } ++rows; } Console.WriteLine("\n共{0}行记录", rows); } reader.Close();//关闭DataReader } catch (Exception ex) { Console.WriteLine("\nError:\n{0}", ex.Message); } } Console.Read(); } }}