日期:2014-05-17  浏览次数:20800 次

新手求教,关于连接数据库的。
刚学C#,数据库一直连不上,总是会有异常。
下面这段代码也是在csdn上找的,sql数据库名称test  表名student  


运行后的结果 


各位大哥,什么地方错了呀?求指教.....
 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=test;Server=(local);";
            strConnection += "Connect Timeout=30";
            using (SqlConnection objConnection = new SqlConnection(strConnection))
            {
                objConnection.Open();
                // method 1
                SqlCommand myCommand = new SqlCommand("select * from student", objConnection);