将UDL用于SqlConnection连接字符串值

时间:2019-08-29 15:46:26

标签: c# sqlconnection

通过我在stackoverflow上搜索到的信息,我认为有90%的问题已解决,但是由于OleDbConnection是如何转换为定义SqlConnection的,因此对具有连接和测试脚本的类的调用需要定义I不确定如何提供。

我已经使用这些页面来获取到目前为止的信息

How to create an SqlConnection in C# to point to UDL file

Calling an SQL Connection method in C#

    private static string CONNECTION_NAME = @"C:\Temp\DisplayDB.udl";

    public static class MyConnection
    {
        public static SqlConnection GetSqlConnection()
        {
            var udlInfo = new OleDbConnection($"File Name={CONNECTION_NAME}");

            return CreateSqlConnection(udlInfo);
        }

        public static SqlConnection CreateSqlConnection(OleDbConnection udlInfo)
        {
            try
            {
                string CONNECTION_STRING = $"Database={udlInfo.Database};Server={udlInfo.DataSource};User ID=User;Password=13245;Integrated Security=True;connect timeout = 30";
                var connection = new SqlConnection(CONNECTION_STRING);
                connection.Open();
                return connection;

            }
            catch
            {
                Console.WriteLine($"{CONNECTION_NAME} Not found");

                return null;
            }

        }
    }

    private void DBCheck()
    {

    // The line below is my issue, mouseover error of ".CreateSqlConnection" 
    // says there is no argument given that corresponds to the required
    // formal parameter 'udlInfo' of
    // 'MainWindow.MyConnection.CreateSqlConnection(OleDbConnection)'

        using (var con = MyConnection.CreateSqlConnection())
        {
            con.Open();
            var command = new SqlCommand("IF DB_ID ('CodeTest') IS NULL " +
                         "BEGIN " +
                         "USE MASTER " +
                         "CREATE DATABASE CodeTest" +
                         " END", con);
            var reader = command.ExecuteReader();
            reader.Close();
            con.Close();
        }
    }

我希望WPF使用UDL文件中的数据库和服务器来建立SqlConnection,以便我可以运行查询和命令。我了解纯文本形式的UDL的安全性部分,但是我不希望使用硬编码的值,因为此应用程序将在各种环境中使用,也不希望这些值在每次启动该应用程序时都需要定义。

0 个答案:

没有答案