最近在写一个上位机程序,需要C#连接SQL Server数据库。在网上找的资料大多通过实际项目来介绍SQL Server的连接和操作,个人觉得不适合我们新手的学习,所以我写篇博客单纯介绍C#连接SQL Server数据库,以及一些操作指令。最后附上一个自制的相关上位机软件,更直观的理解SQL Server的连接。

本文章是建立在已经安装SQL Server数据库的前提,并创建名为“测试"的数据库,以及在该数据库下创建名为”用户账号信息表“的表,表的设计如下图:

一、连接步骤的讲解

1.1引入命名空间

using System.Data.SqlClient;

SQL Server数据提供程序位于System.Data.SqlClient命名空间。

1.2建立连接(SqlConnection类)

//声明一个字符串用于储存连接数据库的字符串
string SqlConnectionStatement = "server=localhost;database=测试;uid=sa;pwd=123456";
//server=localhost代表本机,如果是远程访问可填数据库的IP,端口号默认是1433可以不写
//database=数据库名;uid=用户名(默认是sa);pwd=密码(没有密码可以省略)
SqlConnection conn = new SqlConnection(SqlConnectionStatement);//声明一个SqlConnection对象
conn.Open();//真正与数据库连接

以上三行代码若无错误,运行后系统不报错,即已连接上数据库。

1.3增删查改的代码(SqlCommand类、SqlDataReader类)

(1)插入、更改、删除

SqlCommand cmd = new SqlCommand();//创建一个SqlCommand对象
//设置CommandText对象,设置SQL语句
cmd.CommandText = "insert into 用户账号信息表(用户名,密码,房间数) values ('user1','1234','2')";//插入
//更改:cmd.CommandText = "update 用户账号信息表  set 密码='222' where 用户名='user1'";
//删除:cmd.CommandText = "delete from 用户账号信息表 where 用户名='user1'"
cmd.Connection = conn;//指定连接对象
cmd.ExecuteNonQuery();//执行且仅执行SQL命令,不反回结果集,用于插入、删除、修改命令

(2)查询

SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select 用户名,密码 from 用户账号信息表 where 房间数=2";
cmd.Connection = conn;
SqlDataReader res = cmd.ExecuteReader();//执行SQL语句,并返回一个结果集

 //将返回集保存到一个二位数组中,便于处理。
string[,] vs = new string[6, 2];
for(int i=0;res.Read();i++)
{
    vs[i, 0] = res["用户名"].ToString();
    vs[i, 1] = res["密码"].ToString();
}
res.Close();//关闭SqlDataReader 对象,如果不关闭将不能执行其他SQL语句

创建一个SqlDataReader对象后,再调用SqlDataReader的Read方法读取数据。Read放法使SqlDataReader前进到下一行记录,SqlDataReader的默认位置在第一条记录的前面。因此必须调用Read方法访问数据。

1.4关闭连接

conn.Close();//关闭SqlConnection,释放内存

二、自制软件源码

前端

<Window x:Class="博客_连接SQL_Server.MainWindow"
        xmlns="http://schemas.microsoft/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats/markup-compatibility/2006"
        xmlns:local="clr-namespace:博客_连接SQL_Server"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListBox x:Name="ListBox_Show" HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="500" Margin="150,91,0,0"/>
        <Button x:Name="Button_Insert" Content="插入" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="150,270,0,0" Click="Button_Insert_Click"/>
        <Button x:Name="Button_Delete" Content="删除" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="575,270,0,0" Click="Button_Delete_Click"/>
        <Button x:Name="Button_Update" Content="更改" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="286,270,0,0" Click="Button_Update_Click"/>
        <Button x:Name="Button_Select" Content="查询" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="430,270,0,0" Click="Button_Select_Click"/>

    </Grid>
</Window>

代码实现

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

namespace 博客_连接SQL_Server
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        //声明一个字符串用于储存连接数据库的字符串
        //此处信息根据基础信息的介绍,自行填写
        string SqlConnectionStatement = "server=192.168.71.1;database=测试;uid=sa;pwd=zhongzhi";

        private void Button_Insert_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection conn = new SqlConnection(SqlConnectionStatement);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "insert into 用户账号信息表(用户名, 密码, 房间数) values('user1', '00544', '2')";
            cmd.Connection = conn;
            cmd.ExecuteNonQuery();
            conn.Close();
            Button_Insert.IsEnabled = false;
            Button_Delete.IsEnabled = true;
        }

        private void Button_Update_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection conn = new SqlConnection(SqlConnectionStatement);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "update 用户账号信息表  set 密码='44944' where 用户名='user1'";
            cmd.Connection = conn;
            cmd.ExecuteNonQuery();
            conn.Close();
            Button_Update.IsEnabled = false;
        }

        private void Button_Select_Click(object sender, RoutedEventArgs e)
        {
            //清空ListBox中的数据
            ListBox_Show.Items.Clear();

            SqlConnection conn = new SqlConnection(SqlConnectionStatement);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "select 用户名,密码 from 用户账号信息表";
            cmd.Connection = conn;
            SqlDataReader res = cmd.ExecuteReader();

            int x = 0;
            string[,] vs = new string[6, 2];
            for (int i = 0; res.Read(); i++)
            {
                vs[i, 0] = res["用户名"].ToString();
                vs[i, 1] = res["密码"].ToString();
                x++;
            }
            res.Close();
            
            //为了跟前面讲解相吻合,多写了一个for循环
            for(int i = 0;i<x;i++)
            {
                ListBox_Show.Items.Add("用户名:" + vs[i, 0] + "  " + "密码:" + vs[i, 1]);
            }
        }

        private void Button_Delete_Click(object sender, RoutedEventArgs e)
        {
            //清空ListBox中的数据
            ListBox_Show.Items.Clear();

            SqlConnection conn = new SqlConnection(SqlConnectionStatement);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "delete from 用户账号信息表 where 用户名='user1'";
            cmd.Connection = conn;
            cmd.ExecuteNonQuery();
            conn.Close();
            Button_Delete.IsEnabled = false;
            Button_Insert.IsEnabled = true;
            Button_Update.IsEnabled = true;
        }
    }
}

效果图

结语:软件的代码写的可能很业余,大家批判食用。若此篇文章出现错误,或者大家在学习过程中出现疑问,欢迎大家留言评论。最后希望此篇文章能帮助您解决问题!!

更多推荐

WPF/C#连接SQL Server数据库,以及一些操作指令(初学)