读书人

请教这个数据库连接如何调试

发布时间: 2012-01-30 21:15:58 作者: rapoo

请问这个数据库连接怎么调试?
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strConn= "server=(local);database=Northwind;uid =sa; Pwd=123456 ";

SqlConnection cn=new SqlConnection(strConn);
cn.Open;
SqlCommand cm=new SqlCommand( "select * from categories ",cn);
SqlDataReader dr=cm.ExecuteReader();
dgCust.DataSource=dr;
dgCust.DataBind();
cn.Close;


}
}


调试结果为:


Server Error in '/WebSite2 ' Application.
--------------------------------------------

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

Source Error:


Line 17:
Line 18: SqlConnection cn=new SqlConnection(strConn);
Line 19: cn.Open;
Line 20: SqlCommand cm=new SqlCommand( "select * from categories ",cn);
Line 21: SqlDataReader dr=cm.ExecuteReader();


Source File: d:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite2\Default.aspx.cs Line: 19

--------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210



[解决办法]
少了括号,改成这样
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
string strConn= "server=(local);database=Northwind;user id=sa;password=123456 ";
try
{
SqlConnection cn=new SqlConnection(strConn);
cn.Open(); //这里加上括号
SqlCommand cm=new SqlCommand( "select * from categories ",cn);
SqlDataReader dr=cm.ExecuteReader();
dgCust.DataSource=dr;
dgCust.DataBind();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cn.Close();
}
}
}
}

读书人网 >asp.net

热点推荐