【问题标题】:Specify Sql Server Schema in connectionString C#在 connectionString C# 中指定 Sql Server Schema
【发布时间】:2017-02-03 13:48:46
【问题描述】:

我有一个控制台应用程序正在连接到 Sql Server 并获取一些值。我在 Select(dbo) 中有架构:

        var ds = new DataTable("test");
        var connSqlRemoto = new SqlConnection("Server=myserverIP;Database=myDataBase;User Id=user;Password=pass;Integrated Security=False;Connection Timeout=60");
        connSqlRemoto.Open();
        var nombreBbdd = connSqlRemoto.Database;
        var daASqlRemoto = new SqlDataAdapter();
        var cmdSqlRemoto = new SqlCommand("SELECT * FROM " + nombreBbdd + ".dbo.myTable;", connSqlRemoto);
        cmdSqlRemoto.CommandTimeout = 1200;
        cmdSqlRemoto.Parameters.Clear();
        daASqlRemoto.SelectCommand = cmdSqlRemoto;
        daASqlRemoto.Fill(ds);

我希望架构是动态的。是否可以在连接字符串中传递模式? 像这样的东西不起作用:

 Server=myserverIP;Database=myDataBase/dbo;User Id=user;Password=pass;Integrated Security=False;Connection Timeout=60

Server=myserverIP;Database=myDataBase.otherSchema;User Id=user;Password=pass;Integrated Security=False;Connection Timeout=60

谢谢。

【问题讨论】:

标签: c# sql-server schema connection-string


【解决方案1】:

实现按连接选择架构的最简单方法可能是将架构映射到用户,然后使用正确的用户连接到数据库。这意味着他们将自动查询其默认架构。

【讨论】:

    【解决方案2】:

    没有。您不能通过连接字符串传递架构。但是你可以像这样在 sqlcommand 中传递模式。

    var schema=".dbo." -- you can set it globally or can change dynamically
    cmdSqlRemoto = new SqlCommand("SELECT * FROM " + nombreBbdd + schema + "myTable;", connSqlRemoto);
    

    【讨论】:

    • 是的,但是我在数据库的一个字段中获得了连接字符串,我不想创建另一个字段...
    • 在这种情况下,我建议您将架构与数据库一起保存在同一列中。例如,不是保存“dbname”而是保存“dbname.dbo”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多