我正在使用 MVC4 视图页面,我正在尝试通过单击按钮将数据从文本框中插入到我的 MS SQL 数据库中。我正在努力这样做,我想问题是“con.open()”,但我不知道在哪里声明它。这是我的代码:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<script runat="server">
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GreenEnergyConnectionString1"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into CUSTOMER values ('"+TextBox2.Text+"', '"+TextBox3.Text+"', '"+TextBox4.Text+"','"+TextBox5.Text+"','"+TextBox6.Text+"', '"+TextBox7.Text+"', '"+TextBox8.Text+"')",con);
cmd.ExecuteNonQuery();
con.Close();
TextBox8.Text = "";
TextBox7.Text = "";
TextBox6.Text = "";
TextBox5.Text = "";
TextBox4.Text = "";
TextBox3.Text = "";
TextBox2.Text = "";
}
在我的 web.config 中,我声明了以下内容:
<add namespace="System.Data.SqlClient"/>
<add namespace="System.Configuration"/>