使用SqlConnection命令链接数据库

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

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

把完成代码粘贴如下:

C#:

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

 

namespace connet_to_database
{
    ///


    /// MainWindow.xaml 的交互逻辑
    ///

    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:

        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">
   
       

你可能感兴趣的:(SQL链接方法)