日期:2014-05-16  浏览次数:20672 次

在VS2010中如何链接上SQL SERVER2012 (ODBC方式)
按照教程,我先在控制面板里执行了添加,测试也成功了。


现在我在VS2010中新建项目(win32控制台应用程序)

假设现在我要在main函数中执行对上述数据库一个很简单的查询 就像“exec sql select XXX”这样的,然后把结果存到自己定义的一些变量里。

为了使这些语句生效,必须要在里面连接上那个数据库,那么我应该在main函数之前写些什么代码呢?要include那些文件呢?

我看网上教程几乎都是用MFC在做,由于个人不太懂MFC,只会写win32控制台应用程序,所以就想问问在win32控制台应用程序中怎么链接。。。求大神指教。
------解决方案--------------------

        static void Main(string[] args)
        {
            string connString =‘连接字符串’;
            SqlConnection conn = new SqlConnection(connString);

            try
            {
                // Open the connection
                conn.Open();
                Console.WriteLine("Connection opened.");

               //Do something
              SqlCommand comm = new SqlCommand();
              comm.Connection = conn;
              comm.CommandText = ‘SQL语句’;
              SqlDataReader reader = comm.ExecuteReader();  //还有其他方法可用
              while (reader.Read())
              {
                  reader[str].ToString();
              }


            }
            catch (SqlException e)
            {
                // Display the exception message
                Console.WriteLine("SQL Error: " + e);
            }
            catch (Exception e)
            {
                // Display the exception message
                Console.WriteLine("Error: " + e);
            }
         &nbs