Iis 建網(wǎng)站為什么說沒有該用戶seo推廣顧問
目錄
一.安裝SQLServer
二.在SQLServer中創(chuàng)建一個數(shù)據(jù)庫
1.打開SQL Server? Manager Studio(SSMS)連接服務(wù)器
2.創(chuàng)建新的數(shù)據(jù)庫
3.創(chuàng)建表
三.Visual Studio 配置
1.創(chuàng)建一個簡單的VS項目(本文創(chuàng)建為一個簡單的控制臺項目)
2.添加數(shù)據(jù)庫連接
?四.簡單連通代碼示例
簡單連通代碼示例:
五.在VS中對SQLServer中的Students表進(jìn)行簡單的增刪改查
?
引言:
SQL Server是微軟開發(fā)的關(guān)系數(shù)據(jù)庫管理系統(tǒng),與市面上其他數(shù)據(jù)庫系統(tǒng)相比
SQL Server在企業(yè)級功能,性能優(yōu)化,安全性和集成性方面表現(xiàn)優(yōu)異,適合大中型企業(yè)應(yīng)用
SQLServer的主要功能:
- 數(shù)據(jù)存儲和管理:支持各種數(shù)據(jù)類型,包括結(jié)構(gòu)化數(shù)據(jù),非結(jié)構(gòu)化數(shù)據(jù)和半結(jié)構(gòu)化數(shù)據(jù)
- 安全性:提供了多層次的安全機(jī)制,如數(shù)據(jù)庫加密,用戶權(quán)限管理和審計功能
- 高可用性和災(zāi)難恢復(fù):支持?jǐn)?shù)據(jù)庫鏡像,日志傳送,故障轉(zhuǎn)移群集和Always On可用性組
- 性能優(yōu)化:內(nèi)置性能監(jiān)控和優(yōu)化工具,如索引調(diào)優(yōu),查詢優(yōu)化器和數(shù)據(jù)庫引擎自動調(diào)優(yōu)
- 集成服務(wù):包括SQL Server Integration Services (SSIS),SQL Server Reporting Services (SSRS) 和SQL Server Analysis Services (SSAS),用于數(shù)據(jù)集成,報表生成和數(shù)據(jù)分析
一.安裝SQLServer
當(dāng)我們需要在Visual Studio中連接一個SQLServer數(shù)據(jù)庫或者其他數(shù)據(jù)庫時,我們需要先去其官網(wǎng)下載對應(yīng)的數(shù)據(jù)庫
Visual Studio(VS)是一個集成開發(fā)環(huán)境(IDE),支持多種編程語言和開發(fā)工具
借助Visual Studio,開發(fā)者可以方便的管理和操作SQLServer數(shù)據(jù)庫
二.在SQLServer中創(chuàng)建一個數(shù)據(jù)庫
1.打開SQL Server? Manager Studio(SSMS)連接服務(wù)器
可以將服務(wù)器名稱替換為.(代表本機(jī))
使用Windows身份驗證
然后點擊連接
2.創(chuàng)建新的數(shù)據(jù)庫
在左側(cè)對象資源管理器中右擊"數(shù)據(jù)庫"
選擇"新建數(shù)據(jù)庫"
輸入數(shù)據(jù)庫名稱,點擊確定
這里使用StudentDB作為數(shù)據(jù)庫庫名
3.創(chuàng)建表
展開數(shù)據(jù)庫
選中當(dāng)前數(shù)據(jù)庫
選擇"新建查詢"(快捷鍵Ctrl+N)
添加以下列:
CREATE TABLE Students
(Id INT IDENTITY(1,1) PRIMARY KEY,Name NVARCHAR(50),Age INT,Grade NVARCHAR(10)
)
執(zhí)行SQL語句
然后右鍵"表",單擊刷新,即可在"表"文件夾下找到新建表Students
右鍵Students表,單擊設(shè)計,即可查看當(dāng)前創(chuàng)建的表結(jié)構(gòu)
三.Visual Studio 配置
1.創(chuàng)建一個簡單的VS項目(本文創(chuàng)建為一個簡單的控制臺項目)
2.添加數(shù)據(jù)庫連接
在"服務(wù)器資源管理器"中(視圖->服務(wù)器資源管理器),快捷鍵Ctrl+Alt+S
右鍵"數(shù)據(jù)連接",點擊添加連接
數(shù)據(jù)源選擇SQLServer
服務(wù)器名自動檢索
勾選"信任服務(wù)器證書"
數(shù)據(jù)庫名選擇新建的StudentDB
單擊左下角"測試連接"
最后點擊"確定"
打開解決方案資源管理器(快捷鍵為Ctrl+Alt+L)
右鍵"依賴項"
打開"管理NuGet程序包"
在"瀏覽"塊 搜索SqlClient
單擊Microsoft.Data.SqlClient 進(jìn)行NuGet包的安裝
安裝時跳出接受許可證界面選擇"我接受"
?四.簡單連通代碼示例
在上面的配置完成之后就可以在VS中使用SQLServer了
簡單連通代碼示例:
// 1. 連接字符串
string connectionString = "Server=.;Database=StudentDB;Trusted_Connection=True;TrustServerCertificate=True;";try
{// 2. 創(chuàng)建連接對象using (SqlConnection connection = new SqlConnection(connectionString)){// 3. 打開連接,在using語句塊中會自動關(guān)閉連接connection.Open();// 4. 創(chuàng)建命令對象string sql = "SELECT * FROM Students";SqlCommand cmd = new SqlCommand(sql, connection);// 5. 執(zhí)行查詢并讀取數(shù)據(jù)using (SqlDataReader reader = cmd.ExecuteReader()){while (reader.Read()){// 假設(shè)Students表有id、name和age字段Console.WriteLine($"ID: {reader["id"]}, 姓名: {reader["name"]}, 年齡: {reader["age"]},年級: {reader["grade"]}" );}}}
}
catch (Exception ex)
{Console.WriteLine($"發(fā)生錯誤: {ex.Message}");
}
Console.WriteLine("按任意鍵退出...");
Console.ReadKey();
代碼解釋:
string connectionString = "Server=.;Database=StudentDB;Trusted_Connection=True;TrustServerCertificate=True;";
- 作用:定義用于連接數(shù)據(jù)庫的連接字符串
- 參數(shù)說明:
- Server=.:指定數(shù)據(jù)庫服務(wù)器為本地服務(wù)器(
.
表示本地) - Database=StudentDB:指定要連接的數(shù)據(jù)庫名稱為
StudentDB
- Trusted_Connection=True:使用Windows身份驗證方式連接數(shù)據(jù)庫,而不是使用SQL Server身份驗證
- TrustServerCertificate=True:允許信任服務(wù)器證書,適用于使用自簽名證書的情況,避免SSL證書錯誤
- Server=.:指定數(shù)據(jù)庫服務(wù)器為本地服務(wù)器(
try
{// 數(shù)據(jù)庫操作代碼
}
catch (Exception ex)
{Console.WriteLine($"發(fā)生錯誤: {ex.Message}");
}
- 作用:創(chuàng)建一個SqlConnection對象,用于與數(shù)據(jù)庫建立連接
using
語句:確保在using塊結(jié)束時自動調(diào)用connection.Dispose()方法釋放數(shù)據(jù)庫連接資源,即自動關(guān)閉連接- 參數(shù):傳入之前定義的connectionString
connection.Open();
- 作用:使用Open()方法與數(shù)據(jù)庫建立實際的連接.此時,程序可以與數(shù)據(jù)庫進(jìn)行通信
string sql = "SELECT * FROM Students";
SqlCommand cmd = new SqlCommand(sql, connection);
- 作用:
- 定義要執(zhí)行的SQL查詢語句,這里是選擇Students表中的所有記錄
- 創(chuàng)建一個SqlCommand對象,表示要對數(shù)據(jù)庫執(zhí)行的命令
- 參數(shù):
- sql:SQL查詢字符串。
- connection:之前創(chuàng)建并打開的數(shù)據(jù)庫連接對象
using (SqlDataReader reader = cmd.ExecuteReader())
{while (reader.Read()){// 讀取數(shù)據(jù)并處理}
}
- 作用:
- 調(diào)用ExecuteReader()方法執(zhí)行SQL查詢,返回一個SqlDataReader對象,用于讀取查詢結(jié)果
- 使用?while (reader.Read())循環(huán)遍歷結(jié)果集的每一行數(shù)據(jù)
using
語句:確保reader
對象在使用完畢后自動關(guān)閉并釋放資源
Console.WriteLine($"ID: {reader["id"]}, 姓名: {reader["name"]}, 年齡: {reader["age"]},年級: {reader["grade"]}" );
- 作用:如果在try塊中的任何位置發(fā)生異常,程序會捕獲該異常
- 處理方式:輸出錯誤信息ex.Message,以便了解錯誤的原因
五.在VS中對SQLServer中的Students表進(jìn)行簡單的增刪改查
using Microsoft.Data.SqlClient;namespace StudentDemo
{internal class Program{static string connectionString = "Server=.;Database=StudentDB;Trusted_Connection=True;TrustServerCertificate=True;";static void Main(string[] args){while (true){Console.WriteLine("\n請選擇操作:");Console.WriteLine("1. 查看所有學(xué)生");Console.WriteLine("2. 添加學(xué)生");Console.WriteLine("3. 修改學(xué)生");Console.WriteLine("4. 刪除學(xué)生");Console.WriteLine("5. 退出");string choice = Console.ReadLine();switch (choice){case "1":QueryAllStudents();break;case "2":AddStudent();break;case "3":UpdateStudent();break;case "4":DeleteStudent();break;case "5":return;default:Console.WriteLine("無效的選擇!");break;}}}static void QueryAllStudents(){try{using (SqlConnection connection = new SqlConnection(connectionString)){connection.Open();string sql = "SELECT * FROM Students";using (SqlCommand cmd = new SqlCommand(sql, connection))using (SqlDataReader reader = cmd.ExecuteReader()){while (reader.Read()){Console.WriteLine($"ID: {reader["Id"]}, 姓名: {reader["Name"]}, 年齡: {reader["Age"]}, 年級: {reader["Grade"]}");}}}}catch (Exception ex){Console.WriteLine($"查詢出錯: {ex.Message}");}}static void AddStudent(){try{Console.Write("請輸入姓名:");string name = Console.ReadLine();Console.Write("請輸入年齡:");int age = int.Parse(Console.ReadLine());Console.Write("請輸入年級:");string grade = Console.ReadLine();using (SqlConnection connection = new SqlConnection(connectionString)){connection.Open();string sql = "INSERT INTO Students (Name, Age, Grade) VALUES (@Name, @Age, @Grade)";using (SqlCommand cmd = new SqlCommand(sql, connection)){cmd.Parameters.AddWithValue("@Name", name);cmd.Parameters.AddWithValue("@Age", age);cmd.Parameters.AddWithValue("@Grade", grade);int result = cmd.ExecuteNonQuery();Console.WriteLine($"成功添加 {result} 條記錄");}}}catch (Exception ex){Console.WriteLine($"添加出錯: {ex.Message}");}}static void UpdateStudent(){try{Console.Write("請輸入要修改的學(xué)生ID:");int id = int.Parse(Console.ReadLine());Console.Write("請輸入新的姓名(直接回車表示不修改):");string name = Console.ReadLine();Console.Write("請輸入新的年齡(直接回車表示不修改):");string ageInput = Console.ReadLine();Console.Write("請輸入新的年級(直接回車表示不修改):");string grade = Console.ReadLine();using (SqlConnection connection = new SqlConnection(connectionString)){connection.Open();string sql = "UPDATE Students SET ";List<string> updates = new List<string>();SqlCommand cmd = new SqlCommand();cmd.Connection = connection;if (!string.IsNullOrWhiteSpace(name)){updates.Add("Name = @Name");cmd.Parameters.AddWithValue("@Name", name);}if (!string.IsNullOrWhiteSpace(ageInput)){updates.Add("Age = @Age");cmd.Parameters.AddWithValue("@Age", int.Parse(ageInput));}if (!string.IsNullOrWhiteSpace(grade)){updates.Add("Grade = @Grade");cmd.Parameters.AddWithValue("@Grade", grade);}if (updates.Count > 0){sql += string.Join(", ", updates);sql += " WHERE Id = @Id";cmd.Parameters.AddWithValue("@Id", id);cmd.CommandText = sql;int result = cmd.ExecuteNonQuery();Console.WriteLine($"成功更新 {result} 條記錄");}}}catch (Exception ex){Console.WriteLine($"修改出錯: {ex.Message}");}}static void DeleteStudent(){try{Console.Write("請輸入要刪除的學(xué)生ID:");int id = int.Parse(Console.ReadLine());using (SqlConnection connection = new SqlConnection(connectionString)){connection.Open();string sql = "DELETE FROM Students WHERE Id = @Id";using (SqlCommand cmd = new SqlCommand(sql, connection)){cmd.Parameters.AddWithValue("@Id", id);int result = cmd.ExecuteNonQuery();Console.WriteLine($"成功刪除 {result} 條記錄");}}}catch (Exception ex){Console.WriteLine($"刪除出錯: {ex.Message}");}}}
}
以上代碼實現(xiàn)了四個主要功能:
- QueryAllStudents(): 查詢并顯示所有學(xué)生信息
- AddStudent(): 添加新學(xué)生
- UpdateStudent(): 根據(jù)ID更新學(xué)生信息
- DeleteStudent(): 根據(jù)ID刪除學(xué)生
每個方法都包含了錯誤處理
- 使用參數(shù)化查詢來防止SQL注入
- 在更新操作中,支持只更新用戶輸入的字段
運行程序后,會顯示一個菜單
- 輸入對應(yīng)的數(shù)字(1-5)來執(zhí)行相應(yīng)的操作
- 根據(jù)提示輸入相應(yīng)的信息
- 程序會顯示操作結(jié)果
- 輸入5可以退出程序
?