在C#中操作SQLserver数据库

创建C#“控制台应用(.net framework)”

注意项目名为CsToSqlTest02,或者自行去改变命名空间。

  这段代码是一个C#控制台应用程序,它允许用户通过命令行界面与一个SQL Server数据库进行交互。程序提供了两个主要功能:向数据库插入数据(INSERT)和从数据库查询数据(SELECT)。

完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System;
using System.Data.SqlClient;
using System.Data;
namespace CsToSqlTest02
{
internal class Program
{
private static string ServeToDateBase = "Server = localhost;DataBase = TestData02x01;Trusted_Connection = true;";//连接字符串,用于连接数据库
static string sqlSTR; //= $"insert into UserDataTable_1(userid,userkeyword,username) values('{userid}','{userkeyword}','{username}')";
static string userid ;
static string userkeyword ;
static string username ;

static void Main(string[] args)
{
string a;
Console.WriteLine("输入INSERT在数据库插入数据,输入SELECT查看数据库数据");
a = Console.ReadLine();
if (a == "INSERT")
{
CR();
}

if (a == "SELECT")
{
CK();
}

if (a != "INSERT" && a != "SELECT")
{
Console.WriteLine("指令错误");
}

Console.WriteLine("按任意键关闭");
Console.ReadKey();
}

public static void CR()
{
string a;
Console.WriteLine("请输入ID,keyword,name");
userid = Console.ReadLine();
userkeyword = Console.ReadLine();
username = Console.ReadLine();
sqlSTR = $"insert into UserDataTable_1(userid,userkeyword,username) values('{userid}','{userkeyword}','{username}')";
InsertSQLDateBase(sqlSTR);

Console.WriteLine("按SELECT进行查看,按INSERT继续进行插入,按C退出操作");
a = Console.ReadLine();
if (a == "SELECT") { CK(); }
if (a == "INSERT") { CR(); }
if(a == "C") { return; }

}

public static void CK()
{
string a;

sqlSTR = "select * from UserDataTable_1";
SelectSQLDateBase(sqlSTR);

Console.WriteLine("按SELECT进行查看,按INSERT继续进行插入,按C退出操作");
a = Console.ReadLine();
if (a == "SELECT") { CK(); }
if (a == "INSERT") { CR(); }
if (a == "C") { return; }
}
public static void InsertSQLDateBase(string sqlSTR)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ServeToDateBase;
conn.Open();

SqlCommand cmd = new SqlCommand(sqlSTR, conn);
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
Console.WriteLine($"执行新增语句,受影响的行数{result}");
}
conn.Close();
}

public static void SelectSQLDateBase(string sqlSTR)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ServeToDateBase;
con.Open();

SqlCommand cmd = new SqlCommand(sqlSTR, con);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;

DataSet ds = new DataSet();
adapter.Fill(ds);
con.Close();
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
Console.WriteLine($"{dt.Rows[i]["userid"]} {dt.Rows[i]["userkeyword"]} {dt.Rows[i]["username"]}");
}
}
}
}

一:连接字符串和变量声明

 这里定义了数据库连接字符串ServeToDateBase,它包含了服务器地址、数据库名和连接方式(这里使用的是Windows身份验证)。
 同时声明了三个静态字符串变量用于存储用户输入的ID、关键词和名称,以及一个用于构建SQL语句的字符串变量sqlSTR。
1
2
3
4
5
private static string ServeToDateBase = "Server = localhost;DataBase = TestData02x01;Trusted_Connection = true;";//连接字符串,用于连接数据库
static string sqlSTR; //= $"insert into UserDataTable_1(userid,userkeyword,username) values('{userid}','{userkeyword}','{username}')";
static string userid ;
static string userkeyword ;
static string username ;

二:插入数据库方法(InsertSQLDateBase)

 InsertSQLDateBase方法使用提供的SQL语句打开数据库连接,执行插入操作,并根据受影响的行数给出反馈。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void InsertSQLDateBase(string sqlSTR)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ServeToDateBase;
conn.Open();

SqlCommand cmd = new SqlCommand(sqlSTR, conn);
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
Console.WriteLine($"执行新增语句,受影响的行数{result}");
}
conn.Close();
}

三:查询数据库方法(SelectSQLDateBase)

  SelectSQLDateBase方法使用提供的SQL语句打开数据库连接,执行查询操作,并将结果填充到DataSet中。
  然后关闭连接,并遍历结果集,将每行数据输出到控制台。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static void SelectSQLDateBase(string sqlSTR) 
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ServeToDateBase;
con.Open();

SqlCommand cmd = new SqlCommand(sqlSTR, con);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;

DataSet ds = new DataSet();
adapter.Fill(ds);
con.Close();
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
Console.WriteLine($"{dt.Rows[i]["userid"]} {dt.Rows[i]["userkeyword"]} {dt.Rows[i]["username"]}");
}
}

在使用SQLserver数据库时可能遇见的问题

显示无法连接到服务器

如下
屏幕截图 2024 11 04 221701

解决方法:找到下面这个界面,也就是SQLsever配置管理器。

找到配置管理器中的SQLserver服务

屏幕截图 2024 11 04 221734

将其全部开启这时再去连接数据库就没问题了。

最后附上数据库名称。和数据表名称:

屏幕截图 2024 11 04 222346