• C# 连接 SqlServer 数据库


    目录

    一、创建表

    二、给表添加数据

    三、新建 C# 项目

    四、SqlServerHelper

    五、连接数据库


    一、创建表

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

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

    字段名如下图

    鼠标右键点击,设置主键

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

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

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

    二、给表添加数据

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

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

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

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

    三、新建 C# 项目

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

    界面代码:

    1. <Window x:Class="Lathe.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    6. xmlns:local="clr-namespace:Lathe"
    7. mc:Ignorable="d" WindowStartupLocation ="CenterScreen"
    8. Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
    9. <Grid>
    10. <Button Content="连接数据库" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="32,39,0,0" Click="ConnectDatabase_OnClick" />
    11. Grid>
    12. Window>

    界面逻辑:

    1. using Lathe.SqlServer;
    2. using System;
    3. using System.Data;
    4. using System.Windows;
    5. namespace Lathe
    6. {
    7. ///
    8. /// MainWindow.xaml 的交互逻辑
    9. ///
    10. public partial class MainWindow : Window
    11. {
    12. public MainWindow()
    13. {
    14. InitializeComponent();
    15. }
    16. private void Window_Loaded(object sender, RoutedEventArgs e)
    17. {
    18. }
    19. //连接数据库 点击事件
    20. public void ConnectDatabase_OnClick(object sender, RoutedEventArgs e)
    21. {
    22. }
    23. }
    24. }

    四、SqlServerHelper

    添加一个类 SqlServerHelper

    代码:

    1. using System.Data;
    2. using System.Data.SqlClient;
    3. namespace Lathe.SqlServer
    4. {
    5. internal class SqlServerHelper
    6. {
    7. ///
    8. /// 连接字符串
    9. ///
    10. private string strconn = string.Empty;
    11. public SqlServerHelper(string conn)
    12. {
    13. //读取配置文件
    14. //strconn = ConfigurationManager.AppSettings["Conn"].ToString();
    15. //strconn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    16. strconn = conn;
    17. }
    18. ///
    19. /// 执行增删改SQL语句
    20. ///
    21. /// SQL语句
    22. ///
    23. public int ExecuteNonQuery(string cmdText)
    24. {
    25. using (SqlConnection conn = new SqlConnection(strconn))
    26. {
    27. conn.Open();
    28. return ExecuteNonQuery(conn, cmdText);
    29. }
    30. }
    31. ///
    32. /// 执行增删改SQL语句
    33. ///
    34. /// SqlConnection
    35. /// SQL语句<
    36. ///
    37. public int ExecuteNonQuery(SqlConnection conn, string cmdText)
    38. {
    39. int res;
    40. using (SqlCommand cmd = new SqlCommand(cmdText, conn))
    41. {
    42. cmd.CommandType = CommandType.Text;
    43. res = cmd.ExecuteNonQuery();
    44. if (conn.State == ConnectionState.Open)
    45. {
    46. conn.Close();
    47. conn.Dispose();
    48. }
    49. }
    50. return res;
    51. }
    52. ///
    53. /// 执行查询SQL语句
    54. ///
    55. /// SQL语句
    56. ///
    57. public DataTable ExecuteDataTable(string cmdText)
    58. {
    59. using (SqlConnection conn = new SqlConnection(strconn))
    60. {
    61. conn.Open();
    62. return ExecuteDataTable(conn, cmdText);
    63. }
    64. }
    65. ///
    66. /// 执行查询SQL语句
    67. ///
    68. /// SqlConnection
    69. /// SQL语句
    70. ///
    71. private DataTable ExecuteDataTable(SqlConnection conn, string cmdText)
    72. {
    73. DataTable dt = new DataTable();
    74. using (SqlCommand cmd = new SqlCommand(cmdText, conn))
    75. {
    76. cmd.CommandType = CommandType.Text;
    77. using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
    78. {
    79. sda.Fill(dt);
    80. if (conn.State == ConnectionState.Open)
    81. {
    82. conn.Close();
    83. conn.Dispose();
    84. }
    85. }
    86. }
    87. return dt;
    88. }
    89. ///
    90. /// 执行查询SQL语句
    91. ///
    92. /// SQL语句
    93. ///
    94. public DataTable ExecuteQuery(string cmdText)
    95. {
    96. using (SqlConnection conn = new SqlConnection(strconn))
    97. {
    98. conn.Open();
    99. return ExecuteQuery(conn, cmdText);
    100. }
    101. }
    102. ///
    103. /// 执行查询SQL语句
    104. ///
    105. /// SqlConnection
    106. /// SQL语句
    107. ///
    108. public DataTable ExecuteQuery(SqlConnection conn, string cmdText)
    109. {
    110. DataTable dt = new DataTable();
    111. using (SqlCommand cmd = new SqlCommand(cmdText, conn))
    112. {
    113. using (SqlDataReader sdr = cmd.ExecuteReader())
    114. {
    115. dt.Load(sdr);
    116. sdr.Close();
    117. sdr.Dispose();
    118. if (conn.State == ConnectionState.Open)
    119. {
    120. conn.Close();
    121. conn.Dispose();
    122. }
    123. }
    124. }
    125. return dt;
    126. }
    127. }
    128. }

    五、连接数据库

    修改界面逻辑代码

    1. using Lathe.SqlServer;
    2. using System;
    3. using System.Data;
    4. using System.Windows;
    5. namespace Lathe
    6. {
    7. ///
    8. /// MainWindow.xaml 的交互逻辑
    9. ///
    10. public partial class MainWindow : Window
    11. {
    12. public MainWindow()
    13. {
    14. InitializeComponent();
    15. }
    16. private SqlServerHelper SqlServerHelpers;
    17. private void Window_Loaded(object sender, RoutedEventArgs e)
    18. {
    19. string conn = "server=.;dataBase=Test;uid=sa;pwd=123456";
    20. SqlServerHelpers = new SqlServerHelper(conn);
    21. }
    22. //连接数据库 点击事件
    23. public void ConnectDatabase_OnClick(object sender, RoutedEventArgs e)
    24. {
    25. string sql = "SELECT Names FROM Users";
    26. DataTable dataTable = SqlServerHelpers.ExecuteQuery(sql);
    27. if(dataTable != null)
    28. {
    29. //打印所有列名
    30. string columnName = string.Empty;
    31. for (int i = 0; i < dataTable.Columns.Count; i++)
    32. {
    33. //columnName += dataTable.Columns[i].ColumnName + " | ";
    34. columnName += string.Format("{0}({1}) | ", dataTable.Columns[i].ColumnName, i);
    35. }
    36. Console.WriteLine(columnName);
    37. Console.WriteLine("======================");
    38. //打印每一行的数据
    39. foreach (DataRow row in dataTable.Rows)
    40. {
    41. string columnStr = string.Empty;
    42. foreach (DataColumn column in dataTable.Columns)
    43. {
    44. columnStr += row[column] + " | ";
    45. }
    46. Console.WriteLine(columnStr);
    47. }
    48. }
    49. }
    50. }
    51. }

    运行

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

    end

  • 相关阅读:
    Kubernetes集群+Keepalived+Nginx+防火墙 实例
    debugger调试监听webpack配置文件的代码
    C 语言是“最环保”的编程语言
    Verilog 表达式
    Java基础篇——面向对象大纲梳理总结
    16 拉格朗日定理和函数的单调性
    SpringBoot SpringBoot 开发实用篇 1 热部署 1.2 自动启动热部署
    【毕业设计】基于单片机的录音器设计与实现 - 物联网 嵌入式 stm32
    Java集合面试详解
    一场分销裂变活动,不止是发发朋友圈这么简单
  • 原文地址:https://blog.csdn.net/qq_38693757/article/details/127111382