当前位置导航:炫浪网>>网络学院>>编程开发>>Visual C#教程

c#中连接ODBC数据库

        using System;
        using System.IO;
        using System.Data.SqlClient;
        namespace ConsoleSqlConnection
        {
            /// <summary>
            /// Class1 的摘要说明。
            /// </summary>
            class SqlConnectionClass
            {
                /// <summary>
                /// 应用程序的主入口点。
                /// </summary>
                [STAThread]
                static void Main(string[] args)
                {
                    string strCon = @"server=(local);Integrated Security=true;database=Northwind;uid=sa;pwd=sa";
                    SqlConnection MyCon = new SqlConnection(strCon);
                    // 打开SQL Server数据库
                    try
                    {
                        MyCon.Open();
                        // 浏览数据库
                        string strSQL = @"select * from Customers";
                        SqlCommand MyCommand = new SqlCommand(strSQL, MyCon);
                        // 将检索结果放入SqlDataReader中
                        SqlDataReader MyDataReader = MyCommand.ExecuteReader();
                        Console.WriteLine("显示数据库中的数据");
                        while (MyDataReader.Read())
                        {
                            Console.WriteLine("用户名称:{0} 公司名称:{1} 所在城市:{2}", MyDataReader["CustomerID"].ToString().PadRight(10), MyDataReader["CompanyName"].ToString().PadRight(25), MyDataReader["City"].ToString());
                        }
                        MyDataReader.Close();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("{0}", ex.ToString());
                    }
                    finally
                    {
                        // 使用完毕,关闭数据库
                        MyCon.Close();
                    }
                    Console.ReadLine();
                }
            }
        }

相关内容
赞助商链接