如何在连接字符串中动态输入数据库的服务器名称

编程入门 行业动态 更新时间:2024-10-23 18:20:37
本文介绍了如何在连接字符串中动态输入数据库的服务器名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

that is my code for connecting vb 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上的类别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[^]

连接字符串只是一个字符串。您可以从配置文件中获取连接字符串,根据用户的某些输入来确定它,甚至让用户输入数据库服务器名称。 也许是最简单的方法是使用 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)

更多推荐

如何在连接字符串中动态输入数据库的服务器名称

本文发布于:2023-10-30 22:48:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544225.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   名称   数据库   服务器   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!