c#操作sqlserver数据库的简单示例

时间:2024-01-28 11:25:23 

1.在用windows模式登陆sql server 数据库 简历一个student的数据库,然后新建查询:


create table student
(
 id     int  auto_increment  primary key,
 name char(10) not null,
 sex    char(10) not null,
 age   char(10) not null,  
)

2.在vs中新建一个项目,输入一下代码:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string connSting;
            connSting = "server=localhost;database=student;Integrated Security=True ";
            SqlConnection sConn = new SqlConnection(connSting);
            try
            {
                sConn.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine("链接错误:" + ex.Message);
            }
            string sqlMessage=null;
            sqlMessage = "select * from student";
            SqlCommand sCmd = new SqlCommand(sqlMessage, sConn);

            SqlDataReader sdr = null;
            try
            {
                sdr = sCmd.ExecuteReader();

                Console.WriteLine(" 姓名   性别   年龄 ");
                while (sdr.Read())
                {
                    Console.WriteLine(sdr["name"] +""+ sdr["sex"]+"" + sdr["age"]);
                }
                sConn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
    }
}

3.运行结果将会显示数据库中的数据

标签:c#,sqlserver,数据库
0
投稿

猜你喜欢

  • pytorch中的transforms模块实例详解

    2022-04-25 19:50:58
  • goland使用go mod模式的步骤详解

    2024-05-25 15:16:35
  • MySQL中组合字段之concat()

    2024-01-26 04:36:54
  • 在原窗口还是新窗口打开链接?

    2009-12-07 21:24:00
  • js简单的分页器插件代码实例

    2024-04-29 13:23:22
  • pytorch神经网络从零开始实现多层感知机

    2023-11-27 08:06:11
  • Python代码块及缓存机制原理详解

    2023-07-02 08:12:07
  • 利用Python查看目录中的文件示例详解

    2023-02-06 14:13:28
  • 从零开始实现Vue简单的Toast插件

    2024-05-13 09:13:55
  • Python中pip安装非PyPI官网第三方库的方法

    2021-01-20 15:51:18
  • 使用Python构建Hopfield网络的教程

    2022-12-14 01:27:52
  • IntelliJ IDEA2020.3 新特性(小结)

    2023-12-24 13:33:13
  • Python 使用 attrs 和 cattrs 实现面向对象编程的实践

    2022-05-29 22:38:00
  • vue proxytable代理根路径的同时增加其他代理方式

    2024-05-05 09:09:17
  • Dreamweaver层使用八定律

    2008-05-16 11:41:00
  • js清空form表单中的内容示例

    2023-08-23 16:22:02
  • Python 统计列表中重复元素的个数并返回其索引值的实现方法

    2023-07-15 12:31:24
  • Python编程快速上手——Excel到CSV的转换程序案例分析

    2023-03-20 08:14:01
  • Python Request爬取seo.chinaz.com百度权重网站的查询结果过程解析

    2022-12-01 07:16:59
  • Python实现配置文件备份的方法

    2021-06-11 01:39:03
  • asp之家 网络编程 m.aspxhome.com