如何在连接字符串中动态输入数据库的服务器名称 [英] How do I dynamically input the server name of my database in the connection string

查看:96
本文介绍了如何在连接字符串中动态输入数据库的服务器名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ConnectionString = "Data Source=LUSPOC-PC\LUSPOC;Initial Catalog=Sales_Inventory;Integrated Security=True"



这是我将vb.net连接到MS SQL Server 2014的代码。是否可以从我的GUI输入LUSPOC-PC\LUSPOC,以便可以从不同的数据库服务器使用它?是的如何?



我的尝试:




that is my code for connecting vb.net to MS SQL server 2014. Is it Possible to input "LUSPOC-PC\LUSPOC" from my GUI so that it can be use from different Database servers ? is Yes How ?

What I have tried:

ConnectionString = "Data Source=@SName;Initial Catalog=Sales_Inventory;Integrated Security=True"
Dim cmd As New SqlCommand
cmd.Parameters.AddWithValue("@SName", TextBox1.Text)

推荐答案

参考此演示

如何在C#中使用SqlConnectionStringBuilder [ ^ ]

使用Sq在EzzyLearning.com上的类别ADO.NET中的C#教程中的lConnectionStringBuilder类 [ ^ ]
refer this demo
How to use SqlConnectionStringBuilder in C#[^]
Using SqlConnectionStringBuilder class in C# Tutorial in Category ADO.NET at EzzyLearning.com[^]


连接字符串只是一个字符串。您可以从配置文件中获取连接字符串,根据用户的某些输入来确定它,甚至让用户输入数据库服务器名称。



也许是最简单的方法是使用 SqlConnectionStringBuilder类(System.Data) .SqlClient) [ ^ ]。只需根据需要设置属性,并使用SqlConnection连接字符串的ConnectionString属性。



有关在配置文件中存储连接字符串的信息,请查看连接字符串和配置文件 [ ^ ]



[已添加]

似乎您更新了您尝试过的代码。基于该更新:您不能在连接字符串中使用参数。它不是SQL命令或任何其他命令。



如上所述,使用连接字符串构建器创建连接字符串或将其存储在配置文件中。



例如,请考虑以下内容

The connection string is just a string. You can fetch the connection string from a configuration file, decide it based on some input from the user or even let the user to input the database server name.

Perhaps the easiest way is to use SqlConnectionStringBuilder Class (System.Data.SqlClient)[^]. Just set the properties as you like and the use the ConnectionString property for SqlConnection's connection string.

For information about storing connection string in configuration files, have a look at Connection Strings and Configuration Files[^]

[ADDED]
It seems that you updated the code you've tried. Based on that update: You cannot use parameters in connection string. It is not an SQL command or any other command.

As said, create the connection string with the connection string builder or store it in a configuration file.

As an example, consider the following
Dim connstr As System.Data.SqlClient.SqlConnectionStringBuilder
connstr.InitialCatalog = "Sales_Inventory"
connstr.IntegratedSecurity = True
connstr.DataSource = TextBox1.Text
System.Windows.Forms.MessageBox.Show(connstr.ConnectionString)


这篇关于如何在连接字符串中动态输入数据库的服务器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆