当前位置:网站首页>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 ..........
边栏推荐
- Shiniman household sprint A shares: annual revenue of nearly 1.2 billion red star Macalline and incredibly home are shareholders
- 「连续学习Continual learning, CL」最新2022研究综述
- Y48. Chapter III kubernetes from introduction to mastery -- pod status and probe (21)
- leetcode:1567. Length of the longest subarray whose product is a positive number [dp[i] indicates the maximum length ending with I]
- 线性模型LN、单神经网络SNN、深度神经网络DNN与CNN测试对比
- [LeetCode]-链表-2
- Is it safe for CICC fortune to open an account? I want to open an account to speculate in stocks.
- CVPR 2022 | 美团技术团队精选论文解读
- Record a redis large key troubleshooting
- SAP Commerce Cloud 项目 Spartacus 入门
猜你喜欢
第2章 构建自定义语料库
亿级月活全民K歌Feed业务在腾讯云MongoDB中的应用及优化实践
MATLAB与Mysql数据库连接并数据交换(基于ODBC)
Redis + Guava 本地缓存 API 组合,性能炸裂!
【protobuf 】protobuf 升级后带来的一些坑
「连续学习Continual learning, CL」最新2022研究综述
众多碎石3d材质贴图素材一键即可获取
Godson China Science and technology innovation board is listed: the market value is 35.7 billion yuan, becoming the first share of domestic CPU
leetcode:6107. 不同骰子序列的数目【dp六个状态 + dfs记忆化】
In 2022, where will the medium and light-weight games go?
随机推荐
leetcode:1567. Length of the longest subarray whose product is a positive number [dp[i] indicates the maximum length ending with I]
传纸条【动态规划】
第2章 构建自定义语料库
Leetcode question brushing: String 01 (inverted string)
在哪个平台买股票开户最安全?求分享
y48.第三章 Kubernetes从入门到精通 -- Pod的状态和探针(二一)
Test comparison of linear model LN, single neural network SNN, deep neural network DNN and CNN
Shiniman household sprint A shares: annual revenue of nearly 1.2 billion red star Macalline and incredibly home are shareholders
Which securities company is the most convenient, safe and reliable for opening an account
关于appium踩坑 :Encountered internal error running command: Error: Cannot verify the signature of (已解决)
Convolutional neural network (CNN) explanation and tensorflow2 code implementation
SAP Spartacus 中的依赖注入 Dependency Injection 介绍
指南针能开户炒股吗?安全吗?
[LeetCode]-链表-2
MacOS环境下使用HomeBrew安装[email protected]
Icml2022 | neurotoxin: a lasting back door to federal learning
Background search, how to find the website background
Matrix derivation and its chain rule
leetcode:152. Product maximum subarray [consider DP of two dimensions]
卷积神经网络(CNN)详解及TensorFlow2代码实现