我有一个asp.net
应用程序,它是一个随机的地方生成器。
目前我在我的代码后面的值,但我想将它们移动到我的SQL Server数据库,但我不知道如何做到这一点。作为参考,我使用的是SQL Server Management Studio。
这是可能的还是我只是让它复杂化了?
代码背后
protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
List<string> Eat = new List<string>();
Eat.Add("Chinese Buffet");
Eat.Add("Harvester");
Eat.Add("Frankie & Benny's");
Eat.Add("Hungry Horse");
Eat.Add("Blaize");
Eat.Add("Chiquito");
Eat.Add("Cafe Football");
Eat.Add("Nando's");
Random Place = new Random();
int Places = Place.Next(0, Eat.Count);
txtDestination.Text = Eat[Places];
}
查看
<div class="row">
<div class="col-sm-3">
<asp:TextBox class="form-control" ID="txtDestination" runat="server" disabled></asp:TextBox>
</div>
<div class="col-sm-2">
<asp:Button class="btn btn-success" ID="BtnDecideForMe" runat="server" Text="Decide For Me" OnClick="BtnDecideForMe_Click" />
</div>
</div>
建议代码但无法正常工作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace PaydayLunchGenerator
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=DEV-116\\ONLINE;" +
"Initial Catalog=PaydayLunch;" +
"Integrated Security=True;";
conn.Open();
//using (SqlConnection conn = new SqlConnection(PaydayLunchConnectionString1))
using (SqlCommand cmd = new SqlCommand("dbo.GetRandomPlace", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("@OutputVar", SqlDbType.VarChar).Direction = ParameterDirection.Output;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from @OutputVar
string place = Convert.ToString(cmd.Parameters["@OutputVar"].Value);
conn.Close();
txtDestination.Text = place;
}
}
}
}
答案 0 :(得分:2)
您可以通过在SQL Server中创建视图并将该视图加载到数据集中来实现此目的。这样,您可以从数据集中进行选择,并在需要时刷新数据。
注意 - 您甚至可以更进一步,创建一个存储过程,只需根据需要从表中提供随机值:)
使用输出变量创建存储过程,然后在内部创建一个像这样的选择
CREATE PROC sp_RandomPlace
@OutputVar nvarchar(100) OUTPUT
AS
SET @OutputVar = (select top 1 percent Place from [PlaceTable] order by newid())
然后在你的c#
中using(SqlConnection conn = new SqlConnection(ConnectionString ))
using(SqlCommand cmd = new SqlCommand("dbo.sp_RandomPlace", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("@OutputVar", SqlDbType.Nvarchar).Direction = ParameterDirection.Output;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from @OutputVar
string place= Convert.ToString(cmd.Parameters["@OutputVar"].Value);
conn.Close();
}
上面的代码未经测试,但你得到了jist
答案 1 :(得分:0)
感谢Alec,我最终使用以下方法使其工作:
libraryDependencies += "cc.factorie" %% "factorie" % "1.2-SNAPSHOT" artifacts( Artifact("factorie", "", "jar"))