C#下的数据库操作

本文主要介绍了使用C#进行数据库操作的相关内容。包括通过OLE、OracleClient、SqlClient等方式连接Access、Oracle、SqlServer数据库,还涉及命令行使用、DataReader和DataSet的运用,以及不同类型存储过程(无输入、有输入、有返回、有输出参数)的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

                                 一:数据库部分
数据库连接:
1:OLE方式连接(主要是对Access数据库系统)
    using System.Data.OleDb;
    OleDbConnection thisConnection = new OleDbConnection(
        @"Provider=Microsoft.Jet.OLEDB.4.0;" +  
        @"Data Source=" +      
        @"C:/Program Files/Microsoft.NET/FrameworkSDK" +
        @"/Samples/QuickStart/aspplus/samples/portal/data/portal.mdb");
2:对Oracle数据库的连接
using System.Data.OracleClient;
OracleConnection thisConnection = new OracleConnection(
        "SERVER=nineaye;" +
        "UID=scott;" +
        "PASSWORD=tiger;"
3:对SqlServer数据库的连接
using System.Data.SqlClient;
SqlConnection thisConnection = new SqlConnection();
thisConnection.ConnectionString =
            @"Server=(local)/NetSDK;" +    
            "Integrated Security=SSPI;" +
            "Connection Timeout=5;" ;

命令行的使用
1:无参数的命令的执行,插入语句
SqlConnection thisConnection = new SqlConnection
    (@"Server=(local)/NetSDK;"  
    "Integrated Security=SSPI;" + 
    "Connection Timeout=5;"     + 
    "Database=tempdb;" );       
     SqlCommand nonqueryCommand = thisConnection.CreateCommand();
     thisConnection.Open();
     nonqueryCommand.CommandText = "CREATE TABLE MyTmpTable (COL1 integer)";
     nonqueryCommand.ExecuteNonQuery() ;
     nonqueryCommand.CommandText = "INSERT INTO MyTmpTable VALUES (37)";
     nonqueryCommand.ExecuteNonQuery();
又一例
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
nonqueryCommand.CommandText =
   "INSERT INTO Employees (Firstname, Lastname) " +
   "VALUES ('Zachariah', 'Zinn')";
nonqueryCommand.ExecuteNonQuery();

2:返回单个值的SQL语句
SqlCommand selectCommand =
   new SqlCommand("SELECT COUNT(*) FROM Employees", thisConnection);
selectCommand.ExecuteScalar();

3:有参数的命令的执行
SqlConnection thisConnection = new SqlConnection
    (@"Server=(local)/NetSDK;"    +
    "Integrated Security=SSPI;" +  
    "Connection Timeout=5;"     +  
    "Database=tempdb;" );      

SqlCommand nonqueryCommand = thisConnection.CreateCommand();
nonqueryCommand.CommandText =
              "INSERT INTO MyTable VALUES (@MyName, @MyNumber)" ;
nonqueryCommand.Parameters.Add("@MyName", SqlDbType.VarChar, 30);
nonqueryCommand.Parameters.Add("@MyNumber", SqlDbType.Int);
nonqueryCommand.Prepare();
nonqueryCommand.Parameters["@MyName"].Value ="张三";
nonqueryCommand.Parameters["@MyNumber"].Value = 95001;

DataReader使用
1:返回结果集的使用
string ConStr = @"server=(local)/NetSDK;" +
        "Integrated Security=SSPI;database=Northwind";
SqlConnection sqlConn = new SqlConnection(ConStr);
sqlConn.Open();
string SQL = "SELECT ContactName FROM Customers";
           SqlCommand sqlComm= new SqlCommand(SQL,sqlConn);     
          SqlDataReader sqlReader = sqlComm.ExecuteReader();
          while(sqlReader.Read())
           {
               Console.WriteLine("{0}", sqlReader[0]);
          }
 sqlReader.Close();
2:返回表的结构如表的列名
string ConStr = @"server=(local)/NetSDK;" +
        "Integrated Security=true;" +
        "database=Northwind";
      SqlConnection sqlConn = new SqlConnection(ConStr);
      try
      {
        sqlConn.Open();

        string Sql = "SELECT * FROM Employees";
        SqlCommand sqlCom = new SqlCommand(Sql,sqlConn);
        SqlDataReader sqlReader = sqlCom.ExecuteReader();
      
        DataTable schemaTable = sqlReader.GetSchemaTable();

        /* Display data structure info of each row in the
         * returned DataTable, which describes
         * one column in the original table */
        foreach (DataRow dRow in schemaTable.Rows)
        {
          foreach (DataColumn dCol in schemaTable.Columns)
            Console.WriteLine(dCol.ColumnName + " = " + dRow[dCol]);
      
        }

        sqlReader.Close();
      }


DataSet使用
1:利用DataSet修改数据库内容
string conStr = @"server=(local)/NetSDK;" +
      "Integrated Security=true;" +
      "database=Northwind";
    SqlConnection Conn = new SqlConnection(conStr);
    try
    {
      string SQL = "SELECT * FROM Employees " +
        "WHERE Country = 'UK'";
      SqlDataAdapter da = new SqlDataAdapter();
      da.SelectCommand = new SqlCommand(SQL,Conn);
      //填充DataSet
      DataSet ds = new DataSet();     
      da.Fill(ds, "Employees");
     //取得DataSet中的表Employees
      DataTable dt = ds.Tables["Employees"];
    //使表的列FirstName不能为空
      dt.Columns["FirstName"].AllowDBNull = false;
    //修改表的第一行的FirstName    
      dt.Rows[0]["FirstName"] = "Wrox Press";

      //增加新的一行
      DataRow newRow = dt.NewRow();
      newRow["FirstName"]="Julian";
      newRow["LastName"] = "Skinner";
      newRow["TitleOfCourtesy"] = "Mr.";
      newRow["City"] = "Birmingham";
      dt.Rows.Add(newRow);

      // 显示DataSet结果
      foreach(DataRow r in dt.Rows)
      {
        Console.WriteLine("{0} {1} {2}",
          r["FirstName"].ToString().PadRight(15),
          r["LastName"].ToString().PadLeft(25),
          r["City"]);
      }

      // 使对客户段的修改返回到数据库中
      SqlCommandBuilder sqlCb = new SqlCommandBuilder(da);
      da.Update(ds,"Employees");
    }
    catch(Exception ex)
    {
      Console.WriteLine("Error Orccured: " + ex.Message);
      Conn.Close();
    }
    finally
    {
   
      Conn.Close();
      Console.ReadLine();
    }
  }  
2:填充并显示DataSet
string conStr = @"server=(local)/NetSDK;" +
      "Integrated Security=true;" +
      "database=Northwind";

    SqlConnection sqlConn = new SqlConnection(conStr);

    try
    {
      sqlConn.Open();

      string SQL = "SELECT ProductName, UnitPrice " +
        "FROM Products WHERE UnitPrice < 20";

      SqlDataAdapter da = new SqlDataAdapter(SQL, sqlConn);

      // Create a DataSet
      DataSet ds = new DataSet();     
        
      // Populate the DataSet with the Products table
      da.Fill(ds, "Products");

      // Get reference to the DataTable object for the Products table
      DataTable dt = ds.Tables["Products"];

      // Display data stored in the DataTable
      foreach (DataRow dRow in dt.Rows)
      {
        foreach (DataColumn dCol in dt.Columns)
          Console.WriteLine(dRow[dCol]);
        Console.WriteLine("=================");
      }
    }
    catch(Exception ex)
    {
      // Catch an exception thrown, if any, and display
      Console.WriteLine("Error: " + ex.Message);
      sqlConn.Close();
    }
    finally
    {
      // Close active connection object
      sqlConn.Close();
      Console.ReadLine();
    }
  }  
3: 使用 DataSet的WriteXML方法将数据库表内容用XML文件显示
using System;
using System.Data;
using System.Data.SqlClient;

class WriteXML
{
  static void Main()
  {
    string conStr = @"server=(local)/NetSDK;" +
      "Integrated Security=true;" +
      "database=Northwind";

    SqlConnection sqlConn = new SqlConnection(conStr);
    sqlConn.Open();

    string SQL = "SELECT ProductName, UnitPrice FROM Products";
    SqlDataAdapter da = new SqlDataAdapter(SQL, sqlConn);
    DataSet ds = new DataSet("MyDataSet");     
    da.Fill(ds, "Products");
  
    ds.WriteXml(@"c:/BegCSharpDB/Chapter8_Examples/ProductsTable.xml");
    sqlConn.Close();
  }
}
4:将 DataSet 与控件DataGrid绑定起来
string ConStr = @"server=(local)/NetSDK;" +
        "Integrated Security=SSPI;" +
        "database=Northwind";
   
      // SQL Query
      string SQL = "SELECT * FROM Customers";
      SqlConnection Conn = new SqlConnection(ConStr);
      SqlDataAdapter da = new SqlDataAdapter(SQL, Conn);
      DataSet ds = new DataSet();

      // Fill DataSet with data
      da.Fill(ds, "Customers");

      // Bind the whole table to the DataGrid control
      dataGrid1.SetDataBinding(ds, "Customers");
5:将 DataSet 与控件DataGrid绑定并将DataGrid做的修改返回到数据库
private System.Windows.Forms.DataGrid dataGrid1;
    private System.Data.DataSet dataSet1;
    private System.Data.SqlClient.SqlCommand sqlCommand1;

    private SqlCommandBuilder sqlCb;
    private SqlDataAdapter da;
    private System.Windows.Forms.Button buttonUpdate;
private void Form1_Load(object sender, System.EventArgs e)
    {
      string ConStr = @"server=(local)/NetSDK;" +
        "Integrated Security=SSPI;" +
        "database=Northwind";
   
      // Get Data from multiple tables table
      string SQL = "SELECT * FROM Employees";

      SqlConnection Conn = new SqlConnection(ConStr);
     
      // Create a SqlCommand object
      sqlCommand1 = new SqlCommand(SQL, Conn);

      // Create a SqlDataAdapter object
      da = new SqlDataAdapter();
      da.SelectCommand = sqlCommand1;

      // Create a SqlCommandBuilder object
      sqlCb = new SqlCommandBuilder(da);

      // Fill DataSet with data from Employees table
      da.Fill(dataSet1, "Employees");

      // Bind the DataGrid at run time
      dataGrid1.SetDataBinding(dataSet1, "Employees");

    }
private void buttonUpdate_Click(object sender, System.EventArgs e)
    {
      /* Call the Update method which uses
       * the SqlCommandBuilder to update the data source
       * with modified data */
      da.Update(dataSet1, "Employees");

    }
6:将 DataSet 中父子表与控件DataGrid绑定
 string ConStr = @"server=(local)/NetSDK;" +
        "Integrated Security=SSPI;" +
        "database=Northwind";
   
      // Get Data from multiple tables table
      string SQL = "SELECT * FROM Employees;" +
        "SELECT * FROM Orders";

      SqlConnection Conn = new SqlConnection(ConStr);
      SqlDataAdapter da = new SqlDataAdapter(SQL, Conn);

      // Map default table names to Employees and Orders
      da.TableMappings.Add("Table", "Employees");
      da.TableMappings.Add("Table1", "Orders");

      // Fill DataSet with data from both tables
      da.Fill(dataSet1);

      /* Create a relation between the two distinct tables
       * and add it into the DataSet */
      DataRelation myRel = new DataRelation("EmployeeOrders",
        dataSet1.Tables[0].Columns["EmployeeID"],
        dataSet1.Tables[1].Columns["EmployeeID"]);
      dataSet1.Relations.Add(myRel);

      // Bind the DataGrid at run time
      dataGrid1.SetDataBinding(dataSet1, "Employees");


存储过程的使用
1:无输入参数存储过程的使用

        SqlConnection cn = new SqlConnection(@"Data Source=(local)/NETSDK;" +
          "Integrated Security=SSPI;database=Northwind");
     
        SqlCommand cmd= cn.CreateCommand();
     
        cmd.CommandType= CommandType.StoredProcedure;
        cmd.CommandText="sp_Select_AllEmployees";
       
        cn.Open();
        SqlDataReader dr=cmd.ExecuteReader();
   
        for (int i=0; i< dr.FieldCount; i++)
        {
          dr.GetName(i);
          lvwRS.Columns.Add(c);
        }

         while (dr.Read())
        {               
          for (int i=1 ; i< dr.FieldCount; i++)
          {                
            dr.GetValue(i).ToString();
          }      
        }
    
        dr.Close();
        cn.Close();
    
2:有输入参数的存储过程的使用

        SqlConnection cn = new SqlConnection(@"Data Source=(local)/NETSDK;" +
          "Integrated Security=SSPI;database=Northwind");

        SqlCommand cmd= cn.CreateCommand();

        cmd.CommandType= CommandType.StoredProcedure;
        cmd.CommandText="sp_Orders_ByEmployeeId";

        SqlParameter parInput = cmd.Parameters.Add("@EmployeeId", SqlDbType.Int);
        parInput.Direction = ParameterDirection.Input;
        parInput.Value= Convert.ToInt32(txtEmpId1.Text);
        cn.Open();
       
        SqlDataReader dr=cmd.ExecuteReader();
   
  
        for (int i=0; i< dr.FieldCount; i++)
        {
           dr.GetName(i);    
        }
     
        while (dr.Read())
        {
            for (int i=1 ; i< dr.FieldCount; i++)
             {                
            dr.GetValue(i).ToString();
             }
        }
     
        dr.Close();
        cn.Close();
      }
   
3:有返回参数的存储过程的使用
       
     SqlConnection cn = new SqlConnection(@"Data Source=(local)/NETSDK;" +
          "Integrated Security=SSPI;database=Northwind"); 

        SqlCommand cmd= cn.CreateCommand();
        cmd.CommandType= CommandType.StoredProcedure;
        cmd.CommandText="sp_Orders_MoreThan100";
        SqlParameter parReturn = cmd.Parameters.Add("ReturnValue", SqlDbType.Int);
        parReturn.Direction = ParameterDirection.ReturnValue ;

        cn.Open();

        //execute the command and display the results
        cmd.ExecuteScalar();
        txtReturn.Text= Convert.ToString(cmd.Parameters["ReturnValue"].Value);

        cn.Close();
     
4:有输出参数存储过程的使用

        SqlConnection cn = new SqlConnection(@"Data Source=(local)/NETSDK;" +
          "Integrated Security=SSPI;database=Northwind");

        SqlCommand cmd= cn.CreateCommand();

        cmd.CommandType= CommandType.StoredProcedure;
        cmd.CommandText="sp_Dates_ByEmployeeId";
 
        SqlParameter parInput = cmd.Parameters.Add("@EmployeeId", SqlDbType.Int);
        parInput.Direction = ParameterDirection.Input;
        parInput.Value= Convert.ToInt32(txtEmpId2.Text);

      
        SqlParameter parOutput1 = cmd.Parameters.Add("@EDate",SqlDbType.DateTime);
        parOutput1.Direction = ParameterDirection.Output ;
        SqlParameter parOutput2 = cmd.Parameters.Add("@LDate",SqlDbType.DateTime);
        parOutput2.Direction = ParameterDirection.Output ;
       
        cn.Open();
        cmd.ExecuteNonQuery() ;
        txtEDate.Text= Convert.ToString(parOutput1.Value);
        txtLDate.Text =Convert.ToString(parOutput2.Value);
        cn.Close();
   


前面做项目,有数据库操作太慢。 而且,有一些新的程序员,他们对数据库操作的经验比较欠缺, 而且,.net需要学的东西就非常多,涵盖很多,还要程序员精通数据库,就更加麻烦,没有好多年的经验, 操作数据库的,一检查就有很多问题。所以,根据需要,我就找到了这个 简单的,高效,快速,方便的 .net数据库操作方案。非常直观。不需要懂数据库都能开发了。 找了好久,总算找到了,分享给大家。 ---------------------------- ------------------------------ SqLamdalf1.0 ----------================-----------================--------- .net与数据库最佳操作类。 无缝衔接sql server和.net。 不需要为操作数据库再话费大量的开发时间,节约开发成本,以及更高效,更快速,更方便。 以后将陆续支持更多的数据库。 ----------================-----------================--------- SqLamdalf1.0免费版,欢迎使用。 使用方法: 双击setup.exe 安装以后。 桌面会出现 SqLamdalf 然后直接添加到需要的程序引用中,就可以使用了。 ============================================================== 调用方法: using SqlLamdalf; //工厂方法建立连接字符串 SqlLamdalf.FactoryAnna factorySql = new SqlLamdalf.FactoryAnna(AnnaType.SqlServer, "Persist Security Info=False;Integrated Security=SSPI;Database=数据库名称;Server=sql服务器名称"); //对需要的表的对象建立对象Sql。下面例子中为两个表,目前已经支持9个表: var Sql = factorySql.Create(); //目前支持返回 1实体类Sql.ExecuteEntity,2实体类列表,3表格,4字符串,5int var sdfsf123 = Sql.ExecuteList((a, b) => Sub.Top(8).Select(a.UserId, a.UserName).From(a) ); //目前支持返回 1实体类Sql.ExecuteEntity,2实体类列表,3表格,4字符串,5int var sdfsf123 = Sql.ExecuteList((a, b) => Sub.Top(8).Select(a.UserId, a.UserName).From(a) ); //分页查询如下,注意OrderBy免费版请取消 DataTable dtUser = Sql.ExecuteDataTable((a, b) => Sub.PageSize(12).PageIndex(2).Select(a.UserId.As("ID号"), a.UserName.As("名字")).From(a).OrderBy(a.CreateDate.Desc()) ); //如需执行多条语句,请在语句后面加上Next() var sdfsf1113 = Sql.ExecuteList((a, b) => Sub.Insert(a).Values("213", "111", 11, "2012-02-02"). Next(). Select("213", "111", 11, "2012-02-02").From(a).Where(a.UserId == 123123) ); //下面是联结方式的多表查询,支持各种联结查询,&&意味and,LikeLeft意为Like '%name',LikeRight var sdfsf21 = Sql.ExecuteNonQuery((a, b) => Sub.Update(a).Set(a.RoleId == u1.RoleId, a.LoginPassword == irod.ToString(), a.UserName == "2").From(a). InnerJoin(b).On(a.UserId == b.CategoryId) .Where(a.UserId == 1 && (a.UserName + "123").LikeLeft(u1.UserName)) );
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值