using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;public partial class _Default : System.Web.UI.Page
{
string connString = "server=.; database=2016-9-2;user id=sa; password=123456";
SqlConnection sqlcnn;
SqlCommand sqlcmm;
protected void Page_Load(object sender, EventArgs e)
{
sqlcmm = new SqlCommand();
sqlcnn = new SqlConnection();
sqlcnn.ConnectionString = connString;
sqlcmm.Connection = sqlcnn;
if (!this.IsPostBack)
{
sqlcmm.CommandText = "select * from provinces";
try
{
sqlcnn.Open();
SqlDataReader reader = sqlcmm.ExecuteReader();//reader 指向一个数据集,需要从数据集中将各行数据读出 while (reader.Read())
this.DropDownList1.DataTextField = "name";//要作为文本显示的字段名
this.DropDownList1.DataValueField = "citid";//要作为项的值得字段名
this.DropDownList1.DataSource = reader;//数据源的名称
this.DropDownList1.DataBind();//真正的开始绑定数据
sqlcnn.Close(); }
catch
{
this.Response.Write("<script>alert('获取省份失败!');<script>");
}
//填充城市列表
this.DropDownList1_SelectedIndexChanged(null, null);
}
}
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;public partial class _Default : System.Web.UI.Page
{
string connString = "server=.; database=2016-9-2;user id=sa; password=123456";
SqlConnection sqlcnn;
SqlCommand sqlcmm;
protected void Page_Load(object sender, EventArgs e)
{
sqlcmm = new SqlCommand();
sqlcnn = new SqlConnection();
sqlcnn.ConnectionString = connString;
sqlcmm.Connection = sqlcnn;
if (!this.IsPostBack)
{
sqlcmm.CommandText = "select * from provinces";
try
{
sqlcnn.Open();
SqlDataReader reader = sqlcmm.ExecuteReader();//reader 指向一个数据集,需要从数据集中将各行数据读出 while (reader.Read())
this.DropDownList1.DataTextField = "name";//要作为文本显示的字段名
this.DropDownList1.DataValueField = "citid";//要作为项的值得字段名
this.DropDownList1.DataSource = reader;//数据源的名称
this.DropDownList1.DataBind();//真正的开始绑定数据
sqlcnn.Close(); }
catch
{
this.Response.Write("<script>alert('获取省份失败!');<script>");
}
//填充城市列表
this.DropDownList1_SelectedIndexChanged(null, null);
}
}
sqlcmm.CommandText = "select * from provinces";
sqlcmm.Connection = sqlcnn;
1.先把sql语句放到数据库里查询执行一下,看是否是语句出错。
2.然后设断点调试,看是不是因为代码原因,导致没有连接上数据库。
我暂时遇到的问题都是这么解决的。