从C#code将数据插入到SQL Server [英] Insert data into SQL Server from C# code

查看:164
本文介绍了从C#code将数据插入到SQL Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表学生 ID,名称)。然后,我有一个文本框,用于输入名字,当点击提交按钮,它的数据插入到数据库中。所以,我怎么可以插入只有名称,而不是ID,因为id是自动递增?

这个我试过

 插入学生(ID,姓名)值(,名)

但不插入我的表。

这是我的code:

 保护无效的button1_Click(对象发件人,EventArgs的发送)
{
    字符串测试= txtName.Text;    康涅狄格州的SqlConnection =新的SqlConnection(@数据源= \\ SQLEX $ P $干燥综合征。AttachDbFilename = | DataDirectory目录| \\ Person.mdf;集成安全=真;用户实例=真);    字符串SQL =插入学生(名)VALUES('测试');    尝试
    {
        conn.Open();
        CMD的SqlCommand =新的SqlCommand(SQL,conn);在
        cmd.ExecuteNonQuery();
    }
    赶上(System.Data.SqlClient.SqlException前)
    {
        弦乐味精=插入错误:;
        味精+ = ex.Message;
    }
    最后
    {
        conn.Close();
    }
}


解决方案

  INSERT INTO学生(名)VALUES('名')

省略 ID 列干脆,它会自动填充。要使用您的变量,你应该参数化SQL查询。

  SQL字符串=INSERT INTO学生(姓名)值(@name);
conn.Open();
CMD的SqlCommand =新的SqlCommand(SQL,conn);在
cmd.Parameters.Add(@名,SqlDbType.VarChar);
。cmd.Parameters [@名]值=测试;
cmd.ExecuteNonQuery();

您永远不应该试图通过构建包含输入值的SQL字符串要做到这一点,因为这可以使您的code到SQL注入漏洞。

I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. So how can I insert only to name, not id because id is auto increment?

I tried this

insert into student(id, name) values(,name) 

but it is not insert to my table.

This is my code :

protected void Button1_Click(object sender, EventArgs e)
{
    string test = txtName.Text;

    SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");

    string sql = "insert into student(name) values ('test')";

    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        string msg = "Insert Error:";
        msg += ex.Message;
    }
    finally
    {
        conn.Close();
    }
}

解决方案

INSERT INTO student (name) values ('name')

Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.

string sql = "INSERT INTO student (name) values (@name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@name", SqlDbType.VarChar);
cmd.Parameters["@name"].Value = test;
cmd.ExecuteNonQuery();

You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.

这篇关于从C#code将数据插入到SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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