开发者

Variable Used In DataSource C#

开发者 https://www.devze.com 2023-02-19 16:47 出处:网络
I have the following code but it seems to not connect, just wondering whether i\'m referring to the variable wrong?

I have the following code but it seems to not connect, just wondering whether i'm referring to the variable wrong?

sqlConnectionNW.ConnectionString = "Data Source=@server;Initial Catalog=Northwind;Integrated Security=True";

When I change it to:

sqlConnectionNW.ConnectionString = "Data Source=ISSP\SQLEXPRESS;Initial Catalog=Northwind;Integ开发者_如何学JAVArated Security=True";

It works fine. It's just when I change it to the variable 'server'.


It would be more like this:

string mySQLServer = "ISSP\SQLEXPRESS";

sqlConnectionNW.ConnectionSTring = "Data Source=" + mySQLServer + ";Initial Catalog=Northwind;Integrated Security=True";


when you write something between "" it's recognized as a string, to use a variable you have to write it outside of the ""'s and with a + before it.if some more variable or string is coming behind you must use another + after your variable.

"Data Source=" +variblename+ ";Initial Catalog=Northwind;Integrated Security=True"


You can't have a variable like that in the connection string. You need to do any replacements before using the connection string.


you could use string.format(), this will allow you to use the variable

sqlConnectionNW.ConnectionString = string.format("Data Source={0};Initial Catalog=Northwind;Integrated Security=True",server)


You maybe better off using the SqlConnectionStringBuilder class Sql Connection String Builder

This may allow you to generate the connection string in way more meaningful to you

0

精彩评论

暂无评论...
验证码 换一张
取 消