如何在Umbraco的用户控件中连接Sql server数据库?
我是翁布拉科的新手。我正在尝试使用.net用户控件在翁布拉科开发一个自定义注册页面。为此,我在umbraco数据库中创建了一个名为“registerTable”的自定义表。我只想使用Usercontrol将数据插入到该表中。连接字符串“CM_connection”位于Webconfig文件中 这是密码如何在Umbraco的用户控件中连接Sql server数据库?,umbraco,Umbraco,我是翁布拉科的新手。我正在尝试使用.net用户控件在翁布拉科开发一个自定义注册页面。为此,我在umbraco数据库中创建了一个名为“registerTable”的自定义表。我只想使用Usercontrol将数据插入到该表中。连接字符串“CM_connection”位于Webconfig文件中 这是密码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace thesis
{
public partial class test : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CM_Connection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
Guid guid;
guid = Guid.NewGuid();
string sql = "INSERT INTO registerTable (Firstname) VALUES (@Name)";
cmd.Parameters.AddWithValue("@Name", TextBox1.Text.Trim() );
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
try
{
cmd.ExecuteNonQuery();
Label1.Text = "Registered successfully.";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
}
这将帮助您继续-此代码是Umbraco术语中的宏。它只获取当前数据库的大小——当然,您可以随意更改查询
@using Umbraco.Core
<div>
@{
var context = ApplicationContext.Current;
var databaseContext = context.DatabaseContext;
databaseContext.Database.OpenSharedConnection();
var db = ApplicationContext.Current.DatabaseContext.Database;
var sql = "SELECT (SUM(reserved_page_count) * 8192) FROM sys.dm_db_partition_stats";
var result = db.ExecuteScalar<int>(sql);
}
@if (databaseContext.Database.Connection.State == System.Data.ConnectionState.Open)
{
<span> Database is Open </span>
<span> Size: @result</span>
}
else
{
<span> Database is Closed</span>
}
@使用Umbraco.Core
@{
var context=ApplicationContext.Current;
var-databaseContext=context.databaseContext;
databaseContext.Database.OpenSharedConnection();
var db=ApplicationContext.Current.DatabaseContext.Database;
var sql=“从sys.dm\u db\u partition\u stats中选择(总和(保留页数)*8192)”;
var result=db.ExecuteScalar(sql);
}
@if(databaseContext.Database.Connection.State==System.Data.ConnectionState.Open)
{
数据库已打开
大小:@result
}
其他的
{
数据库已关闭
}
基本上你所做的就是
您需要使用Umbraco.Core进行此操作 你的问题是什么?你有例外吗?你的代码应该是开箱即用的。当我们把它放到.aspx页面时,代码工作得非常好。但是,当我们在Umbraco的一个dotnet控件页面中实现代码时,它就不起作用了。