C#连接数据库?
using System.Data.SqlClient;
using System.Data;
......
public ..{
.
.
.
SqlConnection cnnHouse = new SqlConnection(Application[ "ConnString "].ToString());
SqlCommand cmdHouse = new SqlCommand();
cmdHouse.CommandText = "SELECT col_name,col_text,flag FROM wlba_regContract_model where id= " + m_modid + " and userid = " + m_userid;
cmdHouse.Connection = cnnHouse;
cnnHouse.Open();
.
.
.
}
为何通不过, 我的web.config文件也配置过了。
以下的就通过(两种有什么区别:):
string strcon;
ConnectionStringSettingsCollection connectionStrings = WebConfigurationManager.ConnectionStrings as ConnectionStringSettingsCollection;
strcon = connectionStrings[ "ConnectionString "].ToString();
SqlConnection mysql = new SqlConnection(strcon);
mysql.Open();
SqlCommand mytable = new SqlCommand( "select top 10 * from gulou ",mysql);
SqlDataReader myread = mytable.ExecuteReader();
myread.Read();
String name;
name = myread.GetValue(5).ToString().Trim();
TextBox1.Text = name;
myread.Close();
mytable.Dispose();
mysql.Close();
请指教
------解决方案--------------------你的Application[ "ConnString "]是在什么时候设的?调试的时候看看它的值是不是正确的连接字符串。
------解决方案--------------------Application[ "ConnString "].ToString()所在的配置文件怎么写的?
------解决方案--------------------你需要在Web Config文件中进行配置
如果你觉得麻烦,笔者愿意提供捷径:
private SqlConnection conn()//自定义函数,创建数据库连接
{
string ConnStr= "server=.;database=myMail;uid=sa;pwd=; ";
SqlConnection myConn= new SqlConnection(ConnStr);
return myConn;
}
private void BindData()
{
SqlConnection myConnection=conn();//连接数据库
string queryStr= "select * from MailBoxInformation order by MailID DESC ";
SqlDataAdapter myDataAdapter=new SqlDataAdapter(queryStr,myConnection);
DataSet myDataSet=new DataSet();
myDataAdapter.Fill(myDataSet, "MailBoxInformation ");
//如果有数据,显示
if(myDataSet.Tables[ "MailBoxInformation "].Rows.Count> 0)