使用DataContext进行简单的SQL查询

时间:2015-09-25 06:58:48

标签: c# asp.net sql-server

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

使用

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

不起作用,在整个投注过程中抛出错误。将模板参数更改为“object”也无济于事。

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

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

通常你会想要使用:

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

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

DB.DB().ExecuteSqlCommand(full_query);

希望它有所帮助。

答案 1 :(得分:0)

After a bit of messing around, I found something that works. I am using a class called DatabaseResults to hold the results:

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>>();
    }
}

The method then goes and runs the query, grabbing the headings and putting them in the results objects. It then reads the rows, taking the strings of the column values. "query" is the string passed in. It is the "select" query, with the select bit missing.

            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();
            }

I can't destroy the connection, as it is used by the systems db object, so I need to open and close it. The try/catch/finally makes sure this happens.