将数据插入SQL Server数据库 [英] Insert data into Sql Server database

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

问题描述

我试图将数据输入到我的数据库,但它给我以下错误:


  

无效列名


下面是我的code

 字符串的connectionString =持续安全信息= FALSE;用户ID = SA;密码= 123;初始目录=地址簿;服务器=比拉尔-PC;使用(SqlConnection的连接=新的SqlConnection(的connectionString))
{
  CMD的SqlCommand =新的SqlCommand();  cmd.CommandText =INSERT INTO资料(姓名,PHONENO,地址)VALUES(+ txtName.Text +,+ txtPhone.Text +,+ txtAddress.Text +);;
  cmd.CommandType = CommandType.Text;
  cmd.Connection =连接;  connection.Open();
  cmd.ExecuteNonQuery();
}


解决方案

请尽量使用参数化的SQL查询来保持恶意发生的安全,所以你可以重新安排你code如下:

另外,还要确保你的表有列名匹配名称 PHONENO 地址

 使用(SqlConnection的连接=新的SqlConnection(的connectionString))
{
    CMD的SqlCommand =新的SqlCommand(INSERT INTO资料(姓名,PHONENO,地址)VALUES(@Name,@PhoneNo,@address));
    cmd.CommandType = CommandType.Text;
    cmd.Connection =连接;
    cmd.Parameters.AddWithValue(@名,txtName.Text);
    cmd.Parameters.AddWithValue(@ PHONENO,txtPhone.Text);
    cmd.Parameters.AddWithValue(@地址,txtAddress.Text);
    connection.Open();
    cmd.ExecuteNonQuery();
}

I am trying to enter data into my database, but it is giving me the following error:

Invalid column name

Here's my code

string connectionString = "Persist Security Info=False;User ID=sa;Password=123;Initial Catalog=AddressBook;Server=Bilal-PC";

using (SqlConnection connection = new SqlConnection(connectionString))
{
  SqlCommand cmd = new SqlCommand();

  cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES (" + txtName.Text + "," + txtPhone.Text + "," + txtAddress.Text + ");";
  cmd.CommandType = CommandType.Text;
  cmd.Connection = connection;

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

解决方案

Always try to use parametrized sql query to keep safe from malicious occurrence, so you could rearrange you code as below:

Also make sure that your table has column name matches to Name, PhoneNo ,Address.

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address)");
    cmd.CommandType = CommandType.Text;
    cmd.Connection = connection;
    cmd.Parameters.AddWithValue("@Name", txtName.Text);
    cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
    cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
    connection.Open();
    cmd.ExecuteNonQuery();
}

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

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