SQLserver连接数据库操作
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sql1
{
class Program
{
//连接字符串--连接数据库用
/// <summary>
/// private 私有属性
/// static 静态 应用程序打开, 运行时就在内存中
/// readonly 只读类型
/// @ 转义
/// </summary>
private static readonly string connString = @"Data Source=DESKTOP-9JEHCP6;Initial Catalog=StudentManage;User ID=sa;Password=sa;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
static void Main(string[] args)
{
//定义SQL语句
string sql = "select className from StudentClass where ClassName=N'小程序';";
//连接SQL数据查询
SqlConnection conn = new SqlConnection(connString);//连接数据库(连接数据库实例)
SqlCommand cmd = new SqlCommand(sql, conn); // 发送sql命令
conn.Open(); //打开数据库连接
object result = cmd.ExecuteScalar();
conn.Close();//关闭数据库
//展示数据
Console.WriteLine("班级名称" +result.ToString());
Console.ReadKey();
}
}
}