如何使用C#连接SQL数据库 [英] How to connect SQL database with C#

查看:206
本文介绍了如何使用C#连接SQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据


-connect-SQL-Database-to-your-Csharp-program>如何将SQL数据库连接到C#程序,初学者的教程
[ ^ ]





有两种连接数据库的方式:



1是Windows身份验证

2是数据库身份验证



如果我使用数据库身份验证:



应该是connectionString是这样的吗?





使用(SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = Server = [server_name]; Database = [database_name]; password = = [password_name]; user = [user_name];
//使用此处的代码...
}





我是什么尝试过:



这只是一个关于连接字符串语法的问题。我想知道如果我使用数据库身份验证,我的连接字符串的语法是否正确。

解决方案

虽然密码字段似乎有太多,但它并不遥远=characetrs。

这是我的一个:

这是本地访问,具有集成安全性。

 Connection = Data Source = GRIFF-DESKTOP \ SQLEXPRESS; Initial Catalog = DatabaseName; Integrated Security = True 



远程访问同一个数据库使用SQL authantication

 Connection = Data Source = GRIFF-DESKTOP \ SQLEXPRESS; Initial Catalog = DatabaseName; User id = SQLUserName; Password = SQLUserPassword 



但是不要像那样对它们进行硬编码 - 总是使用某种形式的配置文件来存储它们,因此如果服务器发生变化(或者当你转向生产时)它们可以被更改。


< blockquote>那个并不太难,请看看这个网站上的一些替代方案s,第一个应该可以为你服务,



SQL Server Native Client 11.0 OLE DB提供程序连接字符串 - ConnectionStrings.com [ ^ ]


How to connect SQL Database with C#

according to How to connect SQL Database to your C# program, beginner's tutorial[^]


there is 2 ways to connect to database :

1 is windows authentication
2 is database authentication

if i use database authentication :

should connectionString be like this ?


using(SqlConnection conn = new SqlConnection()) 
{
    conn.ConnectionString = "Server=[server_name];Database=[database_name]; password = = [password_name];user = [user_name];
    // using the code here...
}



What I have tried:

this is just a question about the syntax of the connectionstring. i would like to know if my syntax for the connectionstring is correct if i use database authentication.

解决方案

It's not far off - though the password field appears to have too many "=" characetrs.
Here's one of mine:
This is the local access, with intgrated security.

Connection=Data Source=GRIFF-DESKTOP\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True


And the remote access to the same database used SQL authantication

Connection=Data Source=GRIFF-DESKTOP\SQLEXPRESS;Initial Catalog=DatabaseName;User id=SQLUserName;Password=SQLUserPassword


But don't hard code them like that - always use a configuration file of some form to store them, so they can be changed if the server changes (or when you move to production).


Thatone isn't too difficult, have a look at this site for some of your alternatives, the first one should serve you fine,

SQL Server Native Client 11.0 OLE DB Provider Connection Strings - ConnectionStrings.com[^]


这篇关于如何使用C#连接SQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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