如何将数据插入到asp.net网站的SQL Server? [英] how to insert data into sql server in asp.net website?

查看:131
本文介绍了如何将数据插入到asp.net网站的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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆