在页面加载时,我从查询字符串中提取参数并插入到数据库中。
这是 web.config 文件
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="MyConsString" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=MCAS_TEST;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
</configuration>
这是我的aspx页面编码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Sample Configuration Page</title>
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td>IP_Address:</td>
<td>
<asp:TextBox ID="x" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>MAC_Address:</td>
<td>
<asp:TextBox ID="y" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</div>
<asp:Button ID="Button1" runat="server" Text="Save"/>
</form>
</body>
</html>
aspx 页面后面的 C# 代码是
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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["x"] != null)
{
insertData();
}
}
public void insertData()
{
using (SqlConnection con = new SqlConnection("MyConsString"))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Test(x, y) VALUES(@x, @y)", con))
{
cmd.Parameters.Add(new SqlParameter("x", Request.QueryString["x"]));
cmd.Parameters.Add(new SqlParameter("y", Request.QueryString["y"]));
cmd.ExecuteNonQuery();
}
}
catch (Exception Ex)
{
// Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
Response.Write("Unable To Save Data. Error - " + Ex.Message);
}
}
}
}
现在在执行它时,我遇到初始化字符串的格式不符合从索引 0 开始的规范的错误。
我不明白为什么...