当前位置:网站首页>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

Necessary preparation

SQL Statement writing and execution

To write

perform

Create actuator

ExecuteNonQuery() How to execute

 ExecuteScalar() How to execute

Difference between the two  

 ExecuteReader() How to execute

example :

1- Create a data table

​ edit

2- Insert data into table

3- Modify the data in the table  

4- Delete data in table

5- Read data from 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

VS2022 Connect sqlserver Database tutorial _ Give me peace of mind A3 The blog of -CSDN Blog _vs How to connect to the database sqlserver

  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 ..........

原网站

版权声明
本文为[Give me peace of mind A3]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206262140569469.html