日期:2014-05-19  浏览次数:20718 次

c#数据库连接的问题
源代码如下:
using   System;
using   System.Data;
using   System.Data.OleDb;

class   OleDbProvider
{
static   void   Main(string[]   args)
{
//our   connection   details
string   Constr=@ "server=(local);provider=SQLOLEDB; "+
        "Intergrated   Security=SSPI;database=Northwind ";
               
//pass   connection   OleDbConnection   object
OleDbConnection   OleDbConn=new   OleDbConnection(Constr);
try
{
//open   the   connection   to   reading
OleDbConn.Open();

//oledb   query   string   that   we 'll   use   to   get   data   from   the   database
string   SQL= "select   *   from   employees ";

//pass   the   SQL   query   and   connection   boject   to   the   oledbconnection
OleDbCommand   OleDbComm=new   OleDbCommand(SQL,OleDbConn);
//read   through   each   record   returned
OleDbDataReader   OleDbReader=OleDbComm.ExecuteReader();
Console.WriteLine( "this   program   demonstrates   the   use   of "+
"oledb.net   data   provider ");
Console.WriteLine( "Frist   Name\tLast   Name ");

//read()   advances   the   cursor   to   the   next   record
while(OleDbReader.Read())
{
Console.WriteLine( "{0}\t{1} ",OleDbReader[ "FirstName "].ToString().PadLeft(10),
OleDbReader[ "LastName "].ToString().PadLeft(10));

}

}
catch(Exception   ex)
{
Console.WriteLine( "Error: "+ex.Message);
}
finally
{
OleDbConn.Close();
                        Console.ReadLine();    
}
}
}
我用的SQL SERVER 2000做数据源,本地服务器
执行结果为:Error:无效的授权说明
为什么会抛出异常?

------解决方案--------------------
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source = (local);Initial Catalog = student;Integrated Security = SSPI;Connection TimeOut = 5; ";
// System.Threading.Thread.Sleep(6);
this.Label1.Text = conn.State.ToString();
conn.Open();
SqlCommand cmd = new SqlCommand( "select * from abc ",conn);
SqlDataReader read = cmd.ExecuteReader();
this.DataGrid1.DataSource = "read ";
this.DataGrid1.DataBind();

------解决方案--------------------
楼主写的代码好象连的是ACCESS数据库的,连SQL的话将头文件里的using System.Data.OleDb;改成using System.Data.Sqlclient,然后把代码里的OleDbConnection,OleDbCommand等都改成SqlConnection SqlCommand吧~~