如何连接sql2012 wid c# [英] How to connect sql2012 wid c#

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

问题描述

嘿,我如何将我在sql server 2012中创建的数据库成功连接到c#。帮助赞赏..

解决方案

尝试使用服务器资源管理器窗格在VS中设置连接:

1)打开服务器资源管理器。 />
2)右键单击数据连接并选择添加连接

3)在随后的对话框中,选择您的数据源和数据库,指定安全信息,然后按测试连接按钮。

4)连接工作时,按确定

5)在服务器资源管理器窗格中突出显示数据库,然后查看属性窗格。将显示连接字符串的工作示例,您可以将其复制并粘贴到您的应用程序或配置文件中。

然后它只是代码:

 使用(SqlConnection con =  new  SqlConnection(strConnect))
{
con.Open();
使用(SqlCommand com = new SqlCommand( SELECT iD,description from myTable,con))
{
using using (SqlDataReader reader = com.ExecuteReader())
{
while (reader.Read())
{
int id =( int )reader [ iD];
string desc =( string )reader [ description];
Console.WriteLine( ID:{0} \ n {1}, iD,desc);
}
}
}
}


您可能希望从找到正确的连接字符串开始例如,SQL Server 2012: SQL Server 2012的连接字符串 [ ^ ]。

您可能还需要配置SQL Server以进行远程访问如果你没有在SQL Server所在的同一台机器上运行你的程序:访问远程SQL Server 2012数据库的最低要求 [ ^ ]。



问候,



-Manfred

Hey, how do i connect a database which i hav created in sql server 2012 to c# successfully. Help appreciated..

解决方案

Try setting up a connection in VS with the Server Explorer pane:
1) Open Server Explorer.
2) Right click "Data connections" and select "Add connection"
3) In the dialog that follows, select your DataSource, and database, specify the security info, and press the "Test connection" button.
4) When the connection works, press "OK"
5) Highlight your database in the Server Explorer pane, and look at the Properties pane. A working example of the connection string will be shown, which you can copy and paste into your app or config file.
Then it''s just code:

using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("SELECT iD, description FROM myTable", con))
        {
        using (SqlDataReader reader = com.ExecuteReader())
            {
            while (reader.Read())
                {
                int id = (int) reader["iD"];
                string desc = (string) reader["description"];
                Console.WriteLine("ID: {0}\n    {1}", iD, desc);
                }
            }
        }
    }


You may want to start with finding the correct connection string for SQL Server 2012 here for instance: Connection strings for SQL Server 2012[^].
You may also need to configure your SQL Server for remote access if you''re not running your programs on the same machine where the SQL Server lives: The minimum requirements to access a remote SQL Server 2012 Database[^].

Regards,

—Manfred


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

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