C#数据库操作的3种典型用法

C#数据库操作的3种典型用法

由于最近和数据库打交道,需要用C#SQL Server 2005进行操作,就把近段时间内的最常用的操作做个总结.本人也是第一次用C#操作数据库,所以这三种典型用法对初学者还是挺有帮助的.

 

以下是我在visual studio 2005上写的一个类(连的是SQL Server 2005),已经过测试通过.里面有3个方法比较典型,在此把源码贴出:

using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

using System.Data.SqlClient;

 

namespace DatabaseOperate

{

    class SqlOperateInfo

    {

        //Suppose your ServerName is "a",DatabaseName is "b",UserName is "c", Password is "d"

        private string sqlConnectionCommand = "Data Source=a;Initial Catalog=b;User ID=c;Pwd=d";

 

        //This table contains two columns:KeywordID int not null,KeywordName varchar(100) not null

        private string dataTableName = "Basic_Keyword_Test";

         //sqlUpdateCommand could contain "insert" , "delete" , "update" operate

        private string sqlSelectCommand = "Select KeywordID, KeywordName From Basic_Keyword_Test";

        private string storedProcedureName = "Insert To Basic_Keyword_Test";

        private string sqlUpdateCommand = "Delete From Basic_Keyword_Test Where KeywordID = 1";

 

=========================================================

        public void UseSqlReader()

        {

            SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand);

            SqlCommand sqlCommand = new SqlCommand();

            sqlCommand.CommandType = System.Data.CommandType.Text;

            sqlCommand.Connection = sqlConnection;

            sqlCommand.CommandText = sqlSelectCommand;

 

            sqlConnection.Open();

            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

            while(sqlDataReader.Read())

            {

                //Get KeywordID and KeywordName , You can do anything you like. I just output them.

                int keywordid = (int)sqlDataReader[0];

                //the same as: int keywordid = (int)sqlDataReader["KeywordID"]

                string keywordName = (string)sqlDataReader[1];

                //the same as: string keywordName = (int)sqlDataReader["KeywordName"]

 

                Console.WriteLine("KeywordID = " + keywordid + " , KeywordName = " + keywordName);

            }

 

            sqlDataReader.Close();

            sqlCommand.Dispose();

            sqlConnection.Close();

        }

=========================================================

 

        public void UseSqlStoredProcedure()

        {

            SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand);

            SqlCommand sqlCommand = new SqlCommand();

            sqlCommand.CommandType = CommandType.StoredProcedure;

            sqlCommand.Connection = sqlConnection;

            sqlCommand.CommandText = storedProcedureName;

 

            sqlConnection.Open();

            sqlCommand.ExecuteNonQuery();

            //you can use reader here,too.as long as you modify the sp and let it like select * from ....

 

            sqlCommand.Dispose();

            sqlConnection.Close();

        }

=========================================================       

 

        public void UseSqlDataSet()

        {

            SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand);

            SqlCommand sqlCommand = new SqlCommand();

            sqlCommand.CommandType = System.Data.CommandType.Text;

            sqlCommand.Connection = sqlConnection;

            sqlCommand.CommandText = sqlSelectCommand;

 

            sqlConnection.Open();

            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();

            sqlDataAdapter.SelectCommand = sqlCommand;

            DataSet dataSet = new DataSet();

            //sqlCommandBuilder is for update the dataset to database

            SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

            sqlDataAdapter.Fill(dataSet, dataTableName);

 

            //Do something to dataset then you can update it to Database.Here I just add a row

            DataRow row = dataSet.Tables[0].NewRow();

            row[0] = 10000;

            row[1] = "new row";

            dataSet.Tables[0].Rows.Add(row);

 

            sqlDataAdapter.Update(dataSet, dataTableName);

 

            sqlCommand.Dispose();

            sqlDataAdapter.Dispose();

            sqlConnection.Close();

        }

    }

}

 

以上的程序概括了最典型的用法,也是最基本的用法

 

 

声明:本贴为转帖,原文地址:http://www.knowsky.com/345354.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前面做项目,有数据库操作太慢。 而且,有一些新的程序员,他们对数据库操作的经验比较欠缺, 而且,.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、付费专栏及课程。

余额充值