数据从数据库返回,但也是异常

时间:2017-05-15 10:49:24

标签: c# asp.net sql-server asp.net-web-api

我有一个从数据库中获取数据的方法。数据本身是一个应该针对不同数据库运行的查询。它工作,但不是真的,因为我在终端中看到它写了正确的行,但它也崩溃并给我一个SqlException,说该表是一个无效的对象,但它确实存在。

我试图使用我在之前的项目中使用的不同表格,但它也没有用。这是我第一次使用Web API,所以也许我错过了一些东西。

public List<Object[]> RunQuery(string server, string database, string queryName)
{
    List<Object[]> rows = new List<Object[]>();
    using (SqlConnection conn = createSqlConnection(server))
    {
        SqlCommand comm = conn.CreateCommand();
        comm.CommandText = buildSelect(queryName, database);
        using (SqlDataReader dr = comm.ExecuteReader())
        {
            while (dr.Read())
            {
                if (dr != null && !dr.IsDBNull(0))
                {
                    Object[] row = new Object[dr.FieldCount];
                    int numOfFields = dr.GetValues(row);
                    rows.Add(row);
                }
            }
        }
    }
    return rows;
}

public static string buildSelect(string name, string database)
{
    List<Object> res = new List<Object>();
    string query = "";
    using (SqlConnection conn = createSqlConnection(sysServer))
    {
        query = "SELECT TABLE_NAME, FIELDS, CONDITIONS FROM " + sysDb + ".dbo.SolutionQuery WHERE QUERY_NAME LIKE '" + name + "' AND FK_SOLUTION_NAME LIKE 'Portrait Dialogue'";
        SqlCommand comm = conn.CreateCommand();
        comm.CommandText = query;
        using (SqlDataReader dr = comm.ExecuteReader())
        {
            while (dr.Read()) if (dr != null && !dr.IsDBNull(0)) for (int i = 0; i < dr.FieldCount; i++) res.Add(dr.GetValue(i));
        }
    }
    foreach (var r in res) Debug.WriteLine("DATA SELECTION ROW: " + r);
    //query = "SELECT " + res[0] + " FROM " + database + res[1] + " " + res[2];
    if (query.Contains("**DB**")) query = query.Replace("**DB**", database);
        return query;
}

我在这里叫它

[HttpGet]
[Route("api/solutionquery/runQuery/{server}/{database}/{queryName}")]
public List<Object[]> RunQuery(string server, string database, string queryName)
{
    SolutionRepository repo = new SolutionRepository();
    List<Object[]> res = repo.RunQuery(server, database, queryName);
    return res;
}

以下是我如何制作连接字符串(它是一种扩展方法)

public static SqlConnection createSqlConnection(string server)
{
    string cs = "Server=" + server + ";Integrated Security=true;";
    SqlConnection conn = new SqlConnection(cs);
    conn.Open();
    Debug.WriteLine("connection");
    return conn;
}

编辑:我不使用实体框架

0 个答案:

没有答案