与asp.net页面的SQL连接? [英] Sql connection with asp.net page?

查看:58
本文介绍了与asp.net页面的SQL连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 web.config 中建立了连接。

I've made a connection in web.config.

<configuration>
	<appsettings />
  <connectionstrings>
    <add name="connection" connectionstring="server=.\sqlexpress; AttachdbFilename=Database.mdf; integrated security=true; user instance=true" />
    
  </connectionstrings></configuration>





现在我如何在页面上建立连接并使用按钮访问数据库。



Now how can I make a connection on page and access the database using buttons.

推荐答案

Public void btnsearch_Click(object sender, EventArgs e)
 
         
    {
       SqlConnection con =  new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
        SqlCommand cmd = new SqlCommand("Your query", con);
        cmd.Parameters.AddWithValue("@id",Your parameters value if any);
        cmd.CommandType = CommandType.Text;
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
       
          //data retrieved in dt use it and do further functionality  
        
        
    }







http://forums.asp.net/t/1463330.aspx/1 [ ^ ]


你可以创建一个类作为

you can create a class as
 public class Db
{
	public Db()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    public static SqlConnection GetConnection()
    {
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["cnn"].ToString();
        cn.Open();
        return cn;
    }


}





和使用连接



and Use Of Connection

string strid = "select max(id) from FileRequest";
            SqlCommand cmdid = new SqlCommand(strid,Db.GetConnection());
            SqlDataReader drid = cmdid.ExecuteReader();
            if (drid.Read())
            {
                id = Int32.Parse(drid[0].ToString());
            }
cmdid.Connection.Close();


您可以通过以下代码连接到数据库。



You can connect to database through following code.

string strCon=ConfigurationManager.ConnectionStrings["connection"].ToString();

SqlConnection con =  new SqlConnection(strCon);

strCon.open();


这篇关于与asp.net页面的SQL连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆