当前位置:网站首页>Using C to operate SQLSERVER database through SQL statement tutorial
Using C to operate SQLSERVER database through SQL statement tutorial
2022-06-26 21:48:00 【Give me peace of mind A3】
Catalog
SQL Statement writing and execution
ExecuteNonQuery() How to execute
ExecuteScalar() How to execute
ExecuteReader() How to execute
3- Modify the data in the table
Necessary preparation
You have to have one sqlserver database , And I want to talk to you vs Project to connect .
About VS Connect sqlserver The database tutorial was posted a few days ago , Links are as follows
Call the assembly used to access and control the database . Make sure you actually install the assembly
using System.Data.SqlClient;
Install as follows 
Fill in the connection parameter string
Database server without account and password (windows User authentication ) Write it like this
string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN Give me peace of mind A3 The database of ;Integrated Security=True";
//LAPTOP-82MUPKTO The name of the connected database server
//CSDN Give me peace of mind A3 The database of Database name of the connection Database server with account and password login (sqlserver Identity Authentication ) Write it like this
string connStr = "Data Source= Server name ;Initial Catalog= Database name ;User ID = account number ;Password= password ";Pass the connection parameter string into the database link class , Generate linked objects conn
SqlConnection conn = new SqlConnection(connStr);
//SqlConnection Variable name = new SqlConnection( Parameter strings or variables that store parameter strings );Test the link , The link succeeds without any error
conn.Open();// Open database link , The later you drive, the better
conn.Close();// Close database links , Turn it off when you're done , Don't hang on The necessary preparations have been made OK 了
Let's talk about sql Statement writing and execution .
SQL Statement writing and execution
To write
Let's define a string Type of sql Variables to store our sql sentence ,sql The statement only needs the original syntax , No need to change .
sqlserver This is the general way to create a data table in

Here we turn him into one line , Never mind indenting .
string sql = "create table csdn A data sheet to give me peace of mind 1(name varchar(8) not null)";Someone will ask. , my sql The content of the statement should change continuously , But the format is basically the same . You can't write another one . Actually, it's not that much trouble , use C# Of String.Format() Generate sql Just a statement string .
C# in string.format usage C# in string.format Usage details (IT technology )
For example, the name of the data table I want to create should be replaced , Let's add a placeholder to the table name OK
string tablename="csdn A data sheet to give me peace of mind 1";// I'm the name of the watch
string sql = String.Format("create table {0}(name varchar(8) not null)", tablename);
//tablename The contents of the string will replace the {0}, therefore sql The content of will follow tablename Change by change perform
Create actuator
sql We have written the sentence , Then it will be executed
We call SqlCommand Class generates a sql Statement executors cmd, Pass in sql Statements and linked variables
SqlCommand cmd = new SqlCommand(sql, conn);
// Format : SqlCommand Custom actuator variable name = new SqlCommand(sql String variable , Link variables );We have created the actuator , Next, select the execution method , Different execution methods have different return values .
Special reminder : Remember to open the link before using
conn.Open();ExecuteNonQuery() How to execute
cmd.ExecuteNonQuery();ExecuteScalar() How to execute
cmd.ExecuteScalar();Difference between the two

ExecuteReader() How to execute
cmd.ExecuteReader();The function of this execution method will be explained in detail in the following examples
Special reminder : Please close the connection after execution
conn.Close();example :
1- Create a data table
Create a personal transcript for Xiao Ming
Want to use sql Statement to create a data table
create table Table name
(
Name data type Is it allowed to be empty (null||not null),
Name 2 data type Is it allowed to be empty (null||not null),
Name 3 data type Is it allowed to be empty (null||not null),
……
Name n data type Is it allowed to be empty (null||not null)
)C# Code
using System.Data.SqlClient;// Don't forget , If the header is added, it shows that it has not been called , Please check Nuget package
public static void addtable(string tablename)
{
// Test connection database
string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN Give me peace of mind A3 The database of ;Integrated Security=True";
SqlConnection conn = new SqlConnection(connStr);
// Open database
conn.Open();
// To write sql sentence , Grammar is sql grammar
string sql = String.Format("create table {0}( Course name varchar(11) not null, achievement tinyint not null)", tablename);
SqlCommand cmd = new SqlCommand(sql, conn);
// Intimate , Exception handling is arranged
try
{
cmd.ExecuteNonQuery();
Console.WriteLine(" Data table created successfully ");
}
catch (SqlException ae)
{
Console.WriteLine(" Data table creation failed ");
Console.WriteLine(ae.Message);
}
finally
{
conn.Close();// After the database operation is completed , Need to close database , Free memory
}
}
addtable(" Test results ")
Wuhu takes off
2- Insert data into table
Xiao Ming passed his computer science exam 100 branch , Help him record it
Want to use sql Insert data instructions in
insert into Table name
values
(' data 1',' data 2',' data 3')// The first line of data , There are only a few columns in the table structure , Where it is allowed to be empty, you can just type ''
(' data 1',' data 2',' data 3')// The second row of data , There are only a few columns in the table structure , Where it is allowed to be empty, you can just type '' public static void adddata(string classname,int grade)
{
// Test connection database
string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN Give me peace of mind A3 The database of ;Integrated Security=True";
SqlConnection conn = new SqlConnection(connStr);
// Open database
conn.Open();
// To write sql sentence , Grammar is sql grammar
string sql = String.Format("insert into Test results values('{0}','{1}')",classname,grade);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.ExecuteNonQuery();
Console.WriteLine(" Score entered successfully ");
}
catch (SqlException ae)
{
Console.WriteLine(" Score entry failed ");
Console.WriteLine(ae.Message);
}
finally
{
conn.Close();// After the database operation is completed , Need to close database , Free memory
}
}
data_Control.adddata(" Computer science ",100);
3- Modify the data in the table
I went to , Xiao Ming was found cheating in the exam , achievement 0 branch , Help him change
update Table name
set Name 1=' value ', Name 2=' value ' where filter public static void changedata(string classname,int new_grade)
{
// Test connection database
string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN Give me peace of mind A3 The database of ;Integrated Security=True";
SqlConnection conn = new SqlConnection(connStr);
// Open database
conn.Open();
// To write sql sentence , Grammar is sql grammar
string sql = String.Format("update Test results set achievement ='{0}' where Course name ='{1}'", new_grade,classname);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.ExecuteNonQuery();
Console.WriteLine(" Score modified successfully ");
}
catch (SqlException ae)
{
Console.WriteLine(" Grade modification failed ");
Console.WriteLine(ae.Message);
}
finally
{
conn.Close();// After the database operation is completed , Need to close database , Free memory
}
}
changedata(" Computer science ",0);
4- Delete data in table
Xiao Ming is afraid of being fried with shredded pork with bamboo shoots by his father , Give me a 1 Bao La bribed me to delete this record , I'm sure I won't help him just for a bag of spicy sticks
, But he took 2 The bag is another matter .
delete from Table name where filter public static void delete_data(string classname)
{
// Test connection database
string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN Give me peace of mind A3 The database of ;Integrated Security=True";
SqlConnection conn = new SqlConnection(connStr);
// Open database
conn.Open();
// To write sql sentence , Grammar is sql grammar
string sql = String.Format("delete from Test results where Course name ='{0}'", classname);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.ExecuteNonQuery();
Console.WriteLine(" Results deleted successfully ");
}
catch (SqlException ae)
{
Console.WriteLine(" Failed to delete grade ");
Console.WriteLine(ae.Message);
}
finally
{
conn.Close();// After the database operation is completed , Need to close database , Free memory
}
}
delete_data(" Computer science "); 
Xiao Ming goes home happily , As soon as he left, I wrote back my grades ……
5- Read data from table
The school will print out Xiao Ming's report card .
ExecuteReader() Here comes the usage of , Thank you for seeing here .
The usage is in the following code
select * from Test results public static void get_data()
{
// Test connection database
string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN Give me peace of mind A3 The database of ;Integrated Security=True";
SqlConnection conn = new SqlConnection(connStr);
// Open database
conn.Open();
// To write sql sentence , Grammar is sql grammar
string sql = String.Format("select * from Test results ");
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader();// Define data readers rdr Get the returned data
while (rdr.Read())// Once at a time Read(), Read a row of data from the data
{
string classname=rdr[" Course name "].ToString();// By column name , Get the course name information in this line , because rdr[" Course name "] The return is object type , So we need to carry out type conversion , The following is the same principle
int grade = Convert.ToInt32(rdr[" achievement "]);// By column name , Get the score information in the line
Console.WriteLine(" Course name :{0}, achievement :{1}",classname,grade);
}
conn.Close();// Always ensure that the database is open when reading
}

Xiaoming sadly took his report card and left ..........
边栏推荐
- YOLOv6:又快又准的目標檢測框架開源啦
- Final part of web crawler: send directional messages to 100000 Netease cloud users
- 数据治理啥都干
- Homebrew installation in MacOS environment [email protected]
- Sword finger offer 12 Path in matrix
- random_ normal_ Initializer uses
- CVPR 2022 | 美团技术团队精选论文解读
- leetcode:152. Product maximum subarray [consider DP of two dimensions]
- lotus configurations
- 在线协作文档综合评测 :Notion、FlowUs、Wolai、飞书、语雀、微软 Office、谷歌文档、金山文档、腾讯文档、石墨文档、Dropbox Paper、坚果云文档、百度网盘在线文档
猜你喜欢

关于appium踩坑 :Encountered internal error running command: Error: Cannot verify the signature of (已解决)

亿级月活全民K歌Feed业务在腾讯云MongoDB中的应用及优化实践

Application and Optimization Practice of 100 million level monthly live national karaoke feed service in Tencent cloud mongodb

Cause analysis of 12 MySQL slow queries

网易云信正式加入中国医学装备协会智慧医院分会,为全国智慧医院建设加速...

Leetcode: String 04 (reverse the words in the string)

AI intelligent matting tool - hair can be seen

YOLOv6:又快又准的目標檢測框架開源啦

Background search, how to find the website background

QT环境下配置Assimp库(MinGW编译器)
随机推荐
The importance of using fonts correctly in DataWindow
[leetcode]- linked list-2
360 mobile assistant is the first to access the app signature service system to help distribute privacy and security
Listing of maolaiguang discipline on the Innovation Board: it is planned to raise 400million yuan. Fanyi and fanhao brothers are the actual controllers
VB.net类库(进阶——2 重载)
模块五作业
Is there any risk in registering and opening an account for stock speculation? Is it safe?
基于SSH框架的学生信息管理系统
剑指 Offer II 098. 路径的数目 / 剑指 Offer II 099. 最小路径之和
Redis + guava local cache API combination, performance burst!
在线协作文档综合评测 :Notion、FlowUs、Wolai、飞书、语雀、微软 Office、谷歌文档、金山文档、腾讯文档、石墨文档、Dropbox Paper、坚果云文档、百度网盘在线文档
经典Wide & Deep模型介绍及tensorflow 2代码实现
众多碎石3d材质贴图素材一键即可获取
网络爬虫2:抓取网易云音乐评论用户ID及主页地址
Is there any risk for flush to register and open an account? Is it safe?
如何在 SAP BTP 平台上启用 HANA Cloud 服务
财务费用分析怎么分析
leetcode:6103. Delete the minimum score of the edge from the tree [DFS + connected component + value record of the subgraph]
Twenty five of offer - all paths with a certain value in the binary tree
PostgreSQL notes
