📜  使用C#的基本数据库操作

📅  最后修改于: 2021-05-29 21:30:47             🧑  作者: Mango

在本文中,您将学习如何使用C#中的system.data.SqlClient命名空间执行基本的数据库操作。基本操作是INSERT,UPDATE,SELECT和DELETE。尽管目标数据库系统是SQL Server数据库,但是由于所使用的查询语法是所有关系数据库系统通常都支持的标准SQL,因此可以将相同的技术应用于其他数据库系统。

先决条件: Microsoft SQL Server Management Studio

打开Microsoft SQL Server Management Studio,然后编写以下脚本以在其中创建数据库和表。

create database Demodb;

use Demodb;

CREATE TABLE demo(
    articleID varchar(30) NOT NULL PRIMARY KEY,
    articleName varchar(30) NOT NULL,
);

insert into demo values(1, 'C#');
insert into demo values(2, 'C++');

执行完上述脚本后,将创建名为demo的下表,该表包含以下数据,如屏幕截图所示。

将C#与数据库连接:要使用数据库,首先需要一个连接。与数据库的连接通常由以下提到的参数组成。

  • 数据库名称或数据源:需要建立连接并可以建立连接的数据库名称,或者您可以说一次只能使用一个数据库。
  • 凭据:建立数据库连接所需的用户名和密码。
  • 可选参数:对于每种数据库类型,您可以指定可选参数以提供有关.NET如何连接到数据库以处理数据的更多信息。

注意:在这里,我们使用命令提示符执行这些代码。若要查看结果,可以使用Microsoft SQL Server Management Studio。

代码1# :使用C#连接数据库

// C# code to connect the database
using System;
using System.Data.SqlClient;
  
namespace Database_Operation {
  
class DBConn {
  
    // Main Method
    static void Main()
    {
        Connect();
        Console.ReadKey();
    }
  
    static void Connect()
    {
        string constr;
  
        // for the connection to 
        // sql server database
        SqlConnection conn; 
  
        // Data Source is the name of the 
        // server on which the database is stored.
        // The Initial Catalog is used to specify
        // the name of the database
        // The UserID and Password are the credentials
        // required to connect to the database.
        constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300";
  
        conn = new SqlConnection(constr);
  
        // to open the connection
        conn.Open(); 
  
        Console.WriteLine("Connection Open!");
    
        // to close the connection
        conn.Close(); 
    }
}
}

输出:

Connection Open !

代码2:使用Select语句和SqlDataReader访问C#中的数据

// C# code to demonstrate how 
// to use select statement
using System;
using System.Data.SqlClient;
  
namespace Database_Operation {
  
class SelectStatement{
  
    // Main Method
    static void Main()
    {
        Read();
        Console.ReadKey();
    }
  
    static void Read()
    {
        string constr;
  
        // for the connection to 
        // sql server database
        SqlConnection conn; 
  
        // Data Source is the name of the 
        // server on which the database is stored.
        // The Initial Catalog is used to specify
        // the name of the database
        // The UserID and Password are the credentials
        // required to connect to the database.
        constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300";
  
        conn = new SqlConnection(constr);
  
        // to open the connection
        conn.Open(); 
  
        // use to perform read and write
        // operations in the database
        SqlCommand cmd; 
  
        // use to read a row in
        // table one by one
        SqlDataReader dreader; 
  
        // to sore SQL command and
        // the output of SQL command
        string sql, output = ""; 
  
         // use to fetch rwos from demo table
        sql = "Select articleID, articleName from demo";
  
        // to execute the sql statement
        cmd = new SqlCommand(sql, conn); 
  
        // fetch all the rows 
        // from the demo table
        dreader = cmd.ExecuteReader(); 
  
        // for one by one reading row
        while (dreader.Read()) {
            output = output + dreader.GetValue(0) + " - " + 
                                dreader.GetValue(1) + "\n";
        }
  
        // to display the output
        Console.Write(output); 
  
        // to close all the objects
        dreader.Close();
        cmd.Dispose();
        conn.Close();
    }
}
}

输出:

1 - C#
2 - C++

代码3:使用C#中的Insert语句将数据插入数据库

// C# code for how to use Insert Statement
using System;
using System.Data.SqlClient;
   
namespace Database_Operation {
      
class InsertStatement {
      
    // Main Method
    static void Main()
    {
        Insert();
        Console.ReadKey();
    }
   
    static void Insert()
    {
         string constr;
   
        // for the connection to 
        // sql server database
        SqlConnection conn; 
   
        // Data Source is the name of the 
        // server on which the database is stored.
        // The Initial Catalog is used to specify
        // the name of the database
        // The UserID and Password are the credentials
        // required to connect to the database.
        constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300";
   
        conn = new SqlConnection(constr);
   
        // to open the connection
        conn.Open(); 
   
        // use to perform read and write
        // operations in the database
        SqlCommand cmd; 
          
        // data adapter object is use to 
        // insert, update or delete commands
        SqlDataAdapter adap = new SqlDataAdapter(); 
          
        string sql = "";
          
        // use the defined sql statement
        // against our database
        sql = "insert into demo values(3, 'Python')"; 
          
        // use to execute the sql command so we 
        // are passing query and connection object
        cmd = new SqlCommand(sql, conn); 
          
        // associate the insert SQL 
        // command to adapter object
        adap.InsertCommand = new SqlCommand(sql, conn); 
          
        // use to execute the DML statement against
        // our database
        adap.InsertCommand.ExecuteNonQuery(); 
          
        // closing all the objects
        cmd.Dispose();
        conn.Close();
    }
}
}

输出:

代码4:使用C#中的Update语句将数据更新到数据库中

// C# code for how to use Update Statement
using System;
using System.Data.SqlClient;
   
namespace Database_Operation {
      
class UpdateStatement {
      
    // Main Method
    static void Main()
    {
        Update();
        Console.ReadKey();
    }
   
    static void Update()
    {
       string constr;
    
        // for the connection to 
        // sql server database
        SqlConnection conn; 
    
        // Data Source is the name of the 
        // server on which the database is stored.
        // The Initial Catalog is used to specify
        // the name of the database
        // The UserID and Password are the credentials
        // required to connect to the database.
        constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300";
    
        conn = new SqlConnection(constr);
    
        // to open the connection
        conn.Open(); 
    
        // use to perform read and write
        // operations in the database
        SqlCommand cmd; 
           
        // data adapter object is use to 
        // insert, update or delete commands
        SqlDataAdapter adap = new SqlDataAdapter(); 
           
        string sql = "";
          
        // use the define sql 
        // statement against our database
        sql = "update demo set articleName='django' where articleID=3"; 
          
        // use to execute the sql command so we 
        // are passing query and connection object
        cmd = new SqlCommand(sql, conn); 
          
        // associate the insert SQL
        // command to adapter object
        adap.InsertCommand = new SqlCommand(sql, conn); 
          
        // use to execute the DML statement against 
        // our database 
        adap.InsertCommand.ExecuteNonQuery(); 
          
        // closing all the objects
        cmd.Dispose();
        conn.Close();
    }
}
}

输出:

代码5:使用C#中的Delete语句将数据删除到数据库中

// C# code for how to use Delete Statement
using System;
using System.Data.SqlClient;
   
namespace Database_Operation {
      
class DeleteStatement {
      
    // Main Method
    static void Main()
    {
        Delete();
        Console.ReadKey();
    }
   
    static void Delete()
    {
       string constr;
    
        // for the connection to 
        // sql server database
        SqlConnection conn; 
    
        // Data Source is the name of the 
        // server on which the database is stored.
        // The Initial Catalog is used to specify
        // the name of the database
        // The UserID and Password are the credentials
        // required to connect to the database.
        constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300";
    
        conn = new SqlConnection(constr);
    
        // to open the connection
        conn.Open(); 
    
        // use to perform read and write
        // operations in the database
        SqlCommand cmd; 
           
        // data adapter object is use to 
        // insert, update or delete commands
        SqlDataAdapter adap = new SqlDataAdapter(); 
           
        string sql = "";
          
        // use the define SQL statement 
        // against our database
        sql = "delete from demo where articleID=3"; 
          
        // use to execute the sql command so we 
        // are passing query and connection object
        cmd = new SqlCommand(sql, conn); 
          
        // associate the insert SQL 
        // command to adapter object
        adap.InsertCommand = new SqlCommand(sql, conn); 
          
        // use to execute the DML statement
        // against our database
        adap.InsertCommand.ExecuteNonQuery(); 
          
        // closing all the objects
        cmd.Dispose();
        conn.Close();
    }
}
}

输出: