如何将数据插入到asp.net网站的SQL Server?

编程入门 行业动态 更新时间:2024-10-27 12:37:27
本文介绍了如何将数据插入到asp网站的SQL Server?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想从我的网站中插入数据到SQL Server建立在VS 2008.For,我使用按钮点击事件。我试图显示在YouTube上code,但在code不起作用。它会显示错误在我的网站。

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.

在code。在.aspx.cs文件

The code in .aspx.cs file is

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 = ""; }

} `

推荐答案

好了,让我们来解决这个问题code最多只是一点点。你越来越有:

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(); } }

有两件事情需要注意修改code。

A couple things to note about the modified code.

  • 在它撬动使用语句,以确保资源得到妥善处理。
  • 在它的参数,以确保SQL注入的可能性也不大。
  • 这不是存储连接对象的任何地方,摆脱了存储连接。
  • It's leveraging the using statement 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.

更多推荐

如何将数据插入到asp.net网站的SQL Server?

本文发布于:2023-10-12 17:38:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485409.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   数据   网站   net   asp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!