将visual studio 2017窗体连接到本地SQL服务器 [英] Connecting visual studio 2017 windows form to local SQL server

查看:186
本文介绍了将visual studio 2017窗体连接到本地SQL服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用C#窗体从Visual Studio 2017连接到本地SQL服务器。您能否帮助并提供C#中的示例代码。

解决方案

您好jon58ph,


>>使用C#windows窗体连接到本地SQL服务器Visual Studio 2017


要实现此要求,您需要创建一个"connectionstring"。连接他们。这是一个简单的演示,它将数据读取到"DataGridView"。

 private void Form1_Load(object sender,EventArgs e)
{
/ / builder连接字符串
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
//设置服务器
builder.DataSource = @" datasource name" ;;
//设置数据库
builder.InitialCatalog = @" catalog name" ;;
//使用现有的Windows安全证书访问数据库
builder.IntegratedSecurity = true;

////如果你想使用用户ID和密码
////设置用户名
//builder.UserID =" Kyle" ;;
////设置密码
//builder.Password =" 123456" ;;

使用(SqlConnection sqlconn = new SqlConnection(builder.ConnectionString))
{
SqlCommand sqlcomm = new SqlCommand(" select * from Table_1",sqlconn);
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlcomm);
DataSet ds = new DataSet();
sqlAdapter.Fill(ds," Table_1");
dataGridView1.DataSource = ds.Tables [" Table_1"];
}
}

SQL Server中的属性:



结果:



问候,


凯尔


I was unable to connect to local SQL server using C# windows form Visual Studio 2017. Could you please help and provide sample code in C# as well.

解决方案

Hi jon58ph,

>> connect to local SQL server using C# windows form Visual Studio 2017

To achieve this requirement, you need to create a "connectionstring" to connect them. Here is a simple demo that read data to "DataGridView".

    private void Form1_Load(object sender, EventArgs e)
    {
        // builder connection string
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();  
        // set server
        builder.DataSource = @"datasource name";
        // set database
        builder.InitialCatalog = @"catalog name";
        // access the database using the existing windows security certificate
        builder.IntegratedSecurity = true;

        //// if you want to use user id and password
        //// set user name
        //builder.UserID = "Kyle";
        //// set password
        //builder.Password = "123456";

        using (SqlConnection sqlconn = new SqlConnection(builder.ConnectionString))
        {
            SqlCommand sqlcomm = new SqlCommand("select * from Table_1", sqlconn);
            SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlcomm);
            DataSet ds = new DataSet();
            sqlAdapter.Fill(ds, "Table_1");
            dataGridView1.DataSource = ds.Tables["Table_1"];
        }
    }

Properties in SQL Server:

Result:

Regards,

Kyle


这篇关于将visual studio 2017窗体连接到本地SQL服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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