使用SqlConnection命令链接数据库

本文通过一个简单的C# Windows应用示例,演示如何使用ADO.NET的SqlConnection类连接到SQL Server数据库。代码中展示了建立数据库连接、打开连接以及处理异常的流程。当连接成功时,会在弹窗中显示'connection is ok',反之则提示'connection is fail'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在刚开始的时候,为链接数据库都花了很多的时间,方式很多,日后逐一介绍。

使用ADO.NET的方式对SQL Server进行访问:

把完成代码粘贴如下:

C#:

using System;
using System.Windows;
using System.Data.SqlClient;
using System.Data;

 

namespace connet_to_database
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();//initiate the window
        }

 

        private void sqlconnection_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string constr = "server=10.199.4.103;user id=qcuser;pwd=!qaz2wsx;database=QC_System";//prepare a command for connecting
                SqlConnection con = new SqlConnection(constr);//use Sqlconnection to connect the data source
                con.Open();//open the connection
                MessageBox.Show("connection is ok");//show the result
            }
            catch (Exception)
            {

                MessageBox.Show("connection is fail"); //show the result
            }
           
        }
    }
}

XAML:

<Window x:Name="ConnectToSQL" x:Class="connet_to_database.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:connet_to_database"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button x:Name="sqlconnection" Content="Sqlconnection" HorizontalAlignment="Left" Margin="24,10,0,0" VerticalAlignment="Top" Width="118" Click="sqlconnection_Click" />
        <DataGrid x:Name="dg" HorizontalAlignment="Left" Height="373" Margin="0,37,0,0" VerticalAlignment="Top" Width="792"/>

    </Grid>
</Window>

 

运行界面:

链接成功的界面:

链接失败的界面:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值