C# 连接sql2005 且 查询

看完就全明白了.

 

 

 using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // "uid=sa":连接数据库的用户名为sa.
            // "password=":连接数据库的验证密码为空.他的别名为"pwd",所以我们可以写为"pwd=".
            // "initial catalog=Northwind":使用的数据源为"Northwind"这个数据库.他的别名为"Database",本句可以写成"Database=Northwind".
            // "Server=YourSQLServer":使用名为"YourSQLServer"的服务器.他的别名为"Data Source","Address","Addr".
            // " Connect Timeout=30":连接超时时间为30秒.(根据情况添加)
            // PS:
            //  1.你的SQL Server必须已经设置了需要用户名和密码来登录,否则不能用这样的方式来登录.如果你的SQL Server设置为Windows登录,那么在这里就不需要使用"uid"和"password"这样的方式来登录,而需要使用"Trusted_Connection=SSPI"来进行登录.
            //  2. 如果使用的是本地数据库且定义了实例名,则可以写为"Server=(local)/实例名";如果是远程服务器,则将"(local)"替换为远程服务器的名称或IP地址.
            string strConnection = "Trusted_Connection=SSPI;";
            strConnection += "database=NTF_Navision_enlistment60;Server=CAIXIATA-6BE823;";
            strConnection += "Connect Timeout=30";
            using (SqlConnection objConnection = new SqlConnection(strConnection))
            {
                objConnection.Open();
                // method 1
                SqlCommand myCommand = new SqlCommand("select * from Couse", objConnection);

                Console.WriteLine("open");
                SqlDataReader myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {
                    Console.WriteLine(myReader.GetFieldType(0));
                    Console.WriteLine(myReader.GetFieldType(1));
                    Console.WriteLine(myReader.GetFieldType(2));
                    Console.WriteLine(myReader.GetDecimal(0));
                    Console.WriteLine(myReader.GetDecimal(1));
                    Console.WriteLine(myReader.GetDecimal(2));
                }
                myReader.Close();

                // method 2
                SqlDataAdapter myCommandd = new SqlDataAdapter("select * from Couse", objConnection);
                DataSet ds = new DataSet();
                myCommandd.Fill(ds, "Couse");
                DataTable dt = ds.Tables["couse"];
                Console.WriteLine(dt.Columns[0].ToString());
                Console.WriteLine(dt.DefaultView.Count);
            }
        }
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值