简单的SQL查询与DataContext

本文关键字:DataContext 查询 SQL 简单 | 更新日期: 2023-09-27 18:14:26

我有一个网站连接到SQL Server数据库,我想添加一个简单的SQL查询到它(管理员)。我希望使用DataContext,并运行一个查询,然后将结果作为一个简单的列表返回。有什么办法可以做到吗?

使用

                string full_query = "SELECT " + query;
            IEnumerable<string> results = DB.DB().ExecuteQuery<string>(full_query);

不起作用,在int类型的地方抛出错误。将模板形参改为"object"也没有多大帮助。

所以我需要运行一个select语句,并将结果作为页面上的列表返回。

任何想法?

简单的SQL查询与DataContext

通常情况下,您需要使用:

var results = DB.DB().SqlQuery(full_query);

如果你想插入/更新/删除,你可以使用:

DB.DB().ExecuteSqlCommand(full_query);

希望能有所帮助。

经过一番折腾,我找到了一些可行的方法。我正在使用一个名为DatabaseResults的类来保存结果:

public class DatabaseResults
{
    public List<string> ColumnNames { get; set; }
    public List<List<string>> Rows { get; set; }
    public DatabaseResults()
    {
        ColumnNames = new List<string>();
        Rows = new List<List<string>>();
    }
}

方法然后运行查询,抓取标题并将它们放入结果对象中。然后读取行,获取列值的字符串。"query"是传入的字符串。这是一个"select"查询,缺少了select位。

            DatabaseResults results = new DatabaseResults();
            string full_query = "SELECT " + query;
            DbConnection connection = DB.DB().Connection;
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = full_query;
            try
            {
                using (var reader = command.ExecuteReader())
                {
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        results.ColumnNames.Add(reader.GetName(i));
                    }
                    while (reader.Read())
                    {
                        List<string> this_res = new List<string>();
                        for (int i = 0; i < reader.FieldCount; ++i)
                        {
                            this_res.Add(reader[i].ToString());
                        }
                        results.Rows.Add(this_res);
                    }
                }
            }
            catch (Exception ex)
            {
                results.ColumnNames.Add("Error");
                List<string> this_error = new List<string>();
                this_error.Add(ex.Message);
                results.Rows.Add(this_error);
            }
            finally
            {
                connection.Close();
            }

我不能破坏连接,因为它是由system db对象使用的,所以我需要打开和关闭它。try/catch/最后确保这发生。