使用SqlConnection命令链接数据库
在刚开始的时候,为链接数据库都花了很多的时间,方式很多,日后逐一介绍。
使用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>
运行界面:
链接成功的界面:
链接失败的界面: