我試圖從ASP.NET插入數據到本地SQL Server數據庫中。我從https://www.youtube.com/watch?v=8bNCfUaJPf8以下。也許你可以嘗試先觀看視頻。我對這個過程完全一樣。將數據從ASP.NET插入到本地SQL Server數據庫中
下面是代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
text-align: center;
}
.auto-style2 {
width: 100%;
}
.auto-style3 {
width: 183px;
}
.auto-style4 {
width: 183px;
height: 21px;
}
.auto-style5 {
height: 21px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 class="auto-style1">insert data</h2>
<br />
</div>
<table class="auto-style2">
<tr>
<td class="auto-style4">FirstName :</td>
<td class="auto-style5">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">LastName :</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">City :</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3"> </td>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
</td>
</tr>
</table>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" OnSelecting="SqlDataSource1_Selecting" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource>
</form>
</body>
</html>
下面是代碼隱藏文件:
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;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Table (fname, lname, city) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
}
}
當我試圖插入數據,出現此錯誤:
[SQL注入警報](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 您應該**不**將您的SQL語句連接在一起 - 使用**參數化查詢**來代替,以避免SQL注入 - 檢查[小Bobby表](https://xkcd.com/327/) –