0


C# 连接 SqlServer 数据库

一、创建表

首先,新建一个数据库 Test,然后新建一个表 Users,字段名如下图,因为暂时只是测试,所以不需要太多的列名,安装 SQL Server 和 SQL Server 管理工具这些这里就不过多介绍了,可以参考下面的帖子:

SQL Server 2019 安装教程_熊思宇的博客-CSDN博客_数据库2019安装教程

字段名如下图

鼠标右键点击,设置主键

当 Id 旁边出现一个钥匙状的图标时,则为设置成功。

按 Ctrl + S 进行保存,然后填入 表名,

刷新一下数据库,在表的下面就可以看到刚刚创建的表了

二、给表添加数据

在这里我就不用 SQL 语句了,直接用编辑器操作,只需要随便添加几个列的数据即可。

鼠标右键点击 User 表,选择 编辑前200行。

这里随便添加点击一点数据

那么此时给表添加数据 就完成了

三、新建 C# 项目

这里就新建一个 WPF 项目吧,界面中就一个按钮,其他的什么都没有,

界面代码:

<Window x:Class="Lathe.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:Lathe"
        mc:Ignorable="d" WindowStartupLocation ="CenterScreen"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
    <Grid>
        <Button Content="连接数据库" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="32,39,0,0" Click="ConnectDatabase_OnClick" />
    </Grid>
</Window>

界面逻辑:

using Lathe.SqlServer;
using System;
using System.Data;
using System.Windows;

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

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        //连接数据库 点击事件
        public void ConnectDatabase_OnClick(object sender, RoutedEventArgs e)
        {

        }
    }
}

四、SqlServerHelper

添加一个类 SqlServerHelper

代码:

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

namespace Lathe.SqlServer
{
    internal class SqlServerHelper
    {
        /// <summary>
        /// 连接字符串
        /// </summary>
        private string strconn = string.Empty;

        public SqlServerHelper(string conn)
        {
            //读取配置文件
            //strconn = ConfigurationManager.AppSettings["Conn"].ToString();
            //strconn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            strconn = conn;
        }

        /// <summary>
        /// 执行增删改SQL语句
        /// </summary>
        /// <param name="cmdText">SQL语句</param>
        /// <returns></returns>
        public int ExecuteNonQuery(string cmdText)
        {
            using (SqlConnection conn = new SqlConnection(strconn))
            {
                conn.Open();
                return ExecuteNonQuery(conn, cmdText);
            }
        }

        /// <summary>
        /// 执行增删改SQL语句
        /// </summary>
        /// <param name="conn">SqlConnection</param>
        /// <param name="cmdText">SQL语句<</param>
        /// <returns></returns>
        public int ExecuteNonQuery(SqlConnection conn, string cmdText)
        {
            int res;
            using (SqlCommand cmd = new SqlCommand(cmdText, conn))
            {
                cmd.CommandType = CommandType.Text;
                res = cmd.ExecuteNonQuery();
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
            return res;
        }

        /// <summary>
        /// 执行查询SQL语句
        /// </summary>
        /// <param name="cmdText">SQL语句</param>
        /// <returns></returns>
        public DataTable ExecuteDataTable(string cmdText)
        {
            using (SqlConnection conn = new SqlConnection(strconn))
            {
                conn.Open();
                return ExecuteDataTable(conn, cmdText);
            }
        }

        /// <summary>
        /// 执行查询SQL语句
        /// </summary>
        /// <param name="conn">SqlConnection</param>
        /// <param name="cmdText">SQL语句</param>
        /// <returns></returns>
        private DataTable ExecuteDataTable(SqlConnection conn, string cmdText)
        {
            DataTable dt = new DataTable();
            using (SqlCommand cmd = new SqlCommand(cmdText, conn))
            {
                cmd.CommandType = CommandType.Text;
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    sda.Fill(dt);
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 执行查询SQL语句
        /// </summary>
        /// <param name="cmdText">SQL语句</param>
        /// <returns></returns>
        public DataTable ExecuteQuery(string cmdText)
        {
            using (SqlConnection conn = new SqlConnection(strconn))
            {
                conn.Open();
                return ExecuteQuery(conn, cmdText);
            }
        }

        /// <summary>
        /// 执行查询SQL语句
        /// </summary>
        /// <param name="conn">SqlConnection</param>
        /// <param name="cmdText">SQL语句</param>
        /// <returns></returns>
        public DataTable ExecuteQuery(SqlConnection conn, string cmdText)
        {
            DataTable dt = new DataTable();
            using (SqlCommand cmd = new SqlCommand(cmdText, conn))
            {
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    dt.Load(sdr);
                    sdr.Close();
                    sdr.Dispose();
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                }
            }
            return dt;
        }

    }
}

五、连接数据库

修改界面逻辑代码

using Lathe.SqlServer;
using System;
using System.Data;
using System.Windows;

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

        private SqlServerHelper SqlServerHelpers;

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string conn = "server=.;dataBase=Test;uid=sa;pwd=123456";
            SqlServerHelpers = new SqlServerHelper(conn);
        }

        //连接数据库 点击事件
        public void ConnectDatabase_OnClick(object sender, RoutedEventArgs e)
        {
            string sql = "SELECT Names FROM Users";
            DataTable dataTable = SqlServerHelpers.ExecuteQuery(sql);
            if(dataTable != null)
            {
                //打印所有列名
                string columnName = string.Empty;
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    //columnName += dataTable.Columns[i].ColumnName + " | ";
                    columnName += string.Format("{0}({1}) | ", dataTable.Columns[i].ColumnName, i);
                }
                Console.WriteLine(columnName);
                Console.WriteLine("======================");

                //打印每一行的数据
                foreach (DataRow row in dataTable.Rows)
                {
                    string columnStr = string.Empty;
                    foreach (DataColumn column in dataTable.Columns)
                    {
                        columnStr += row[column] + " | ";
                    }
                    Console.WriteLine(columnStr);
                }
            }
        }
    }
}

运行

这样就获取到了数据库的数据了

end

标签: sql sqlserver

本文转载自: https://blog.csdn.net/qq_38693757/article/details/127111382
版权归原作者 熊思宇 所有, 如有侵权,请联系我们删除。

“C# 连接 SqlServer 数据库”的评论:

还没有评论