如何将数据从SQL导入到c#

本文关键字:导入 SQL 数据 | 更新日期: 2023-09-27 18:09:11

大家好,我正在做一个项目。我的项目保存了课程名称,学分和我的c#到sql的成绩。这没关系。我能应付,但是。我不能把数据拿去计算我的平均成绩。我想把我的成绩数据放在字符串数组中。

如何将数据从SQL导入到c#

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string connStr = "Enter your conneciton string here";
            string SQL = "Enter your SQL here";
            //uncomment lines below
            //SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);
            //DataTable dt = new DataTable();
            //adapter.Fill(dt);
            //simulated table
            DataTable dt = new DataTable();
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Age", typeof(int));
            dt.Columns.Add("City", typeof(string));
            dt.Rows.Add(new object[] { "John", 22, "NY" });
            dt.Rows.Add(new object[] { "Mary", 27, "Boston" });
            dt.Rows.Add(new object[] { "Paul", 18, "Chicago" });

            int count = 0;
            foreach (DataRow row in dt.AsEnumerable())
            {
                Console.WriteLine("Row {0} : {1}", (count++).ToString(), string.Join(",", row.ItemArray.Select(x => x.ToString()).ToArray()));
            }
            Console.ReadLine();
        }
    }
}