C# 如何在asp.net网站的sql server中插入数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18077527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:13:17  来源:igfitidea点击:

how to insert data into sql server in asp.net website?

c#asp.net.netsql-server

提问by user2653867

I tried to insert data into sql server from my website build in vs 2008.For that I used button click event .I tried code shown in youtube but the code doesn't work .It shows error in my website.

我尝试从我的网站构建中将数据插入到 sql server 中 vs 2008。为此,我使用了按钮单击事件。我尝试了 youtube 中显示的代码,但代码不起作用。它在我的网站中显示错误。

The code in .aspx.cs file is

.aspx.cs 文件中的代码是

public partial class _Default : System.Web.UI.Page 
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

protected void Page_Load(object sender, EventArgs e)
{
    conn.Open();
}
protected void btnInsert_Click(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand("insert into Insert    values('"+txtCity.Text+"','"+txtFName.Text+"','"+txtLName.Text+"')",conn);
    cmd.ExecuteNonQuery();
    conn.Close();
    Label1.Visible =true;
    Label1.Text = "Your data inserted successfully";
    txtCity.Text = "";
    txtFName.Text = "";
    txtLName.Text = "";
}

} `

}`

回答by Mike Perrenoud

Okay, let's fix this code up just a little. You're getting there:

好的,让我们稍微修正一下这段代码。你到达那里:

var cnnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var cmd = "insert into Insert values(@City,@FName,@LName)";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
    using (SqlCommand cmd = new SqlCommand(cmd, cnn))
    {
        cmd.Parameters.AddWithValue("@City",txtCity.Text);
        cmd.Parameters.AddWithValue("@FName",txtFName.Text);
        cmd.Parameters.AddWithValue("@LName",txtLName.Text);

        cnn.Open();
        cmd.ExecuteNonQuery();
    }
}

A couple things to note about the modified code.

关于修改后的代码有几点需要注意。

  • It's leveraging the usingstatement to ensure that resources are properly disposed.
  • It's parameterized to ensure that SQL Injection isn't a possibility.
  • It's not storing a connection object anywhere, get rid of that stored connection.
  • 它利用该using语句来确保正确处置资源。
  • 它被参数化以确保 SQL 注入是不可能的。
  • 它不会在任何地方存储连接对象,摆脱存储的连接。

回答by Sasidharan

Creating procedure will avoid sql injection.

SQL

SQL

Create procedure insert
(@City,@FirstName,@LastName)
{
insert into tablename (City,FName,LName)
values(@City,@FirstName,@LastName)
}

C#

C#

SqlConnection con=new sqlconnection("give ur connection string here");
sqlcommand cmd=new sqlcommand();
con.open();
cmd=new sqlcommand("insert",con);
cmd.commandtype=commandtype.storedprocedure;
cmd.parameters.addwithvalue("@City",txtCity.text);
cmd.parameters.addwithvalue("@FName",txtFName.text);
cmd.parameters.addwithvalue("@LNAme",txtLName.text);
cmd.ExecuteNonQuery();
con.close();

回答by Mrinmoy Nandy

**

**

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;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=mrinmoynandy;User ID=**;Password=****");
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void SumbitBtn_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into streg(Name,Father,Mother,Dob,Sex,Category,Maritial,Vill,Po,Ps,Dist,State,Pin,Country) values (@name,@father,@mother,@dob,@sex,@category,@maritial,@vill,@po,@ps,@dist,@state,@pin,@country)", con);
        cmd.Parameters.AddWithValue(@"name", StNumTxt.Text);
        cmd.Parameters.AddWithValue(@"father", FatNumTxt.Text);
        cmd.Parameters.AddWithValue(@"mother", MotNumTxt.Text);
        cmd.Parameters.AddWithValue(@"dob", DobRdp.SelectedDate);
        cmd.Parameters.AddWithValue(@"sex", SexDdl.SelectedItem.Text);
        cmd.Parameters.AddWithValue(@"category", CategoryDdl.SelectedItem.Text);
        cmd.Parameters.AddWithValue(@"maritial", MaritialRbl.SelectedItem.Text);
        cmd.Parameters.AddWithValue(@"vill", VillTxt.Text);
        cmd.Parameters.AddWithValue(@"po", PoTxt.Text);
        cmd.Parameters.AddWithValue(@"ps", PsTxt.Text);
        cmd.Parameters.AddWithValue(@"dist", DistDdl.SelectedItem.Text);
        cmd.Parameters.AddWithValue(@"state", StateTxt.Text);
        cmd.Parameters.AddWithValue(@"pin", PinTxt.Text);
        cmd.Parameters.AddWithValue(@"country", CountryTxt.Text);
        con.Open();        
        con.Close();        
    }
}
Thanks
Mrinmoy Nandy
Phone No.: +91 9800451398

**

**