![](/img/trans.png)
[英]Insert large asp.net control data row wise into sql table using asp.net c#
[英]Insert Data into SQL table using Javascript and ASP.NET
我使用Microsoft Visual Studio 2012作為平台,並創建了Web Forms Project,在他的“ Table”文件夾中創建了數據庫文件“ SimpleDB.mdf”,然后添加了名為“ Table”的新表,該表有兩列-id和Name(string) )。我正在嘗試在從javascript函數調用服務器端函數的同時將字符串數據插入此表的Name列。
這是aspx.cs代碼
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.Web.Services;
namespace ProjectWWW
{
public partial class WebForm1 : System.Web.UI.Page
{
[WebMethod]
public static string InsertData(string ID){
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
{
SqlCommand cmd = new SqlCommand("Insert into Table(Name) values('" + ID + "')", con);
{
con.Open();
cmd.ExecuteNonQuery();
return "True";
}
}
}
}
這是aspx代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ProjectWWW.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Error');
}
</script>
</head>
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
</html>
所以基本上我期望當單擊按鈕提交時,表列“名稱”將填充為“你好”,但是什么也沒有發生,並且該列保持為空(NULL)
在T-SQL中, Table
是保留字,因此我建議您使用[]
方括號將Table
括起來。
嘗試這個:
SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values('" + ID + "')", con);
建議:您的查詢對sql注入攻擊開放。我建議您使用參數化查詢來避免它們。
嘗試這個:
using(SqlConnection con = new SqlConnection(source))
{
using(SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values(@Name)", con))
{
con.Open();
cmd.Parameters.AddWithValue("@Name",ID);
cmd.ExecuteNonQuery();
return "True";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.