简体   繁体   English

对 SQL 服务器使用 C# 时列名无效

[英]Invalid column name while using C# for SQL Server

This is my code in C#.这是我在 C# 中的代码。 I am just trying to add data to my table in the database.我只是想将数据添加到数据库中的表中。 However, I have been having this issue for only ages.但是,我一直有这个问题只有很长时间。 It says:它说:

invalid column name.无效的列名。

Fotograf database is the only database I have and table ODEV1 is the only table I created. Fotograf数据库是我拥有的唯一数据库,表ODEV1是我创建的唯一表。 When I edit data through SQL Server there is not an issue, but when I try it by using Visual Studio C# I have issues.当我通过 SQL 服务器编辑数据时,没有问题,但是当我使用 Visual Studio C# 尝试时,我遇到了问题。

Any help appreciated thank you!任何帮助表示感谢!

这是我创建的表的图像

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace SQL_ORNEK2
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection baglanti = new SqlConnection();
            baglanti.ConnectionString = "Server=LAPTOP-K3JLTUR0; database=Fotograf; integrated security=True";
            SqlCommand komut = new SqlCommand();
            komut.Connection = baglanti;

            string name;
            name = Console.ReadLine().ToString();
            string surname;
            surname = Console.ReadLine().ToString();
            int age;
            age = Convert.ToInt32(Console.ReadLine());
            string job;
            job = Console.ReadLine().ToString();
            komut.CommandText = "INSERT INTO dbo.ODEV1 VALUES('name', 'surname', age, 'job')";
            baglanti.Open();

            int sonuc = komut.ExecuteNonQuery();
            Console.WriteLine(sonuc);

            Console.ReadKey();
            baglanti.Close();
        }
    }
}

Your insert statement is incorrect.您的insert语句不正确。 You're using the list of columns in place of the values to insert.您正在使用列列表代替要插入的值。 It should look something like this:它应该看起来像这样:

insert into dbo.ODEV1 (name, surname, age, job) values ('Harold', 'Green', 25, 'nerd')

To insert the actual data from the variables you read from user input, you'll want to use SQL parameters:要从您从用户输入中读取的变量中插入实际数据,您需要使用 SQL 参数:

komut.Parameters.AddWithValue("@name", name);
komut.Parameters.AddWithValue("@surname", surname);
komut.Parameters.AddWithValue("@age", age);
komut.Parameters.AddWithValue("@job", job);
komut.CommandText = "insert into dbo.ODEV1 (name, surname, age, job) values (@name, @surname, @age, @job)";

If you use SSMS (SQL-Server Management Studio which is free) to create your INSERT INTO statement by right clicking the desired table, select "script table as", select "INSERT To" to a new query window we get this (using a table named Customers).如果您使用 SSMS(免费的 SQL-Server Management Studio)通过右键单击所需的表 select “script table as”,select “INSERT To”来创建您的 INSERT INTO 语句(使用新查询 Z05B8C74CBD92AFBF24 我们名为客户的表)。

INSERT INTO [dbo].[Customer]
           ([FirstName]
           ,[LastName]
           ,[Address]
           ,[City]
           ,[State]
           ,[ZipCode]
           ,[AccountNumber]
           ,[JoinDate])
     VALUES
           (<FirstName, nvarchar(max),>
           ,<LastName, nvarchar(max),>
           ,<Address, nvarchar(max),>
           ,<City, nvarchar(max),>
           ,<State, nvarchar(max),>
           ,<ZipCode, nvarchar(max),>
           ,<AccountNumber, nvarchar(max),>
           ,<JoinDate, datetime2(7),>)

Now change the VALUES section by using a DECLARE for each value.现在通过对每个值使用 DECLARE 来更改 VALUES 部分。

DECLARE @FirstName nvarchar(max)
DECLARE @LastName nvarchar(max)
DECLARE @Address nvarchar(max)
DECLARE @City nvarchar(max)
DECLARE @State nvarchar(max)
DECLARE @ZipCode nvarchar(max)

INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) VALUES (@FirstName,@LastName,@Address,@City,@State,@ZipCode)

Next, create a class rather than placing data operations into Program.cs with a method specific to adding a new record (the following still uses Customers table).接下来,创建一个class,而不是使用特定于添加新记录的方法将数据操作放入Program.cs中(以下仍然使用Customers表)。

Full source where the following code comes from.以下代码来自的完整源代码。

  • An alternate to cmd.Parameters.AddWithValue is cmd.Parameters.Add which provides fine tuning the type of the parameter. cmd.Parameters.AddWithValue 的替代方法是 cmd.Parameters.Add,它提供了对参数类型的微调。

  • The alternate to getting the new primary key if needed is to add a semi-colon to the end of the INSERT INTO and adding SELECT CAST(scope_identity() AS int);如果需要,获取新主键的替代方法是在 INSERT INTO 末尾添加一个分号并添加 SELECT CAST(scope_identity() AS int); then use Convert.ToInt32(cmd.ExecuteScalar()) to get the new key.然后使用 Convert.ToInt32(cmd.ExecuteScalar()) 获取新密钥。 So after testing with SSMS simply paste the query into a string variable and if this does not work there is something else going on.因此,在使用 SSMS 进行测试后,只需将查询粘贴到字符串变量中,如果这不起作用,则会发生其他事情。

    public bool AddCustomer(string FirstName, string LastName, string Address, string City, string State, string ZipCode, ref int NewPrimaryKeyValue) { bool success = false; public bool AddCustomer(string FirstName, string LastName, string Address, string City, string State, string ZipCode, ref int NewPrimaryKeyValue) { bool success = false;

     using (var cn = new SqlConnection { ConnectionString = ConnectionString }) { using (var cmd = new SqlCommand { Connection = cn }) { cmd.CommandText = "INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) " + "VALUES (@FirstName,@LastName,@Address,@City,@State,@ZipCode)"; try { cmd.Parameters.AddWithValue("@FirstName", FirstName); cmd.Parameters.AddWithValue("@LastName", LastName); cmd.Parameters.AddWithValue("@Address", Address); cmd.Parameters.AddWithValue("@City", City); cmd.Parameters.AddWithValue("@State", State); cmd.Parameters.AddWithValue("@ZipCode", ZipCode); cn.Open(); int result = cmd.ExecuteNonQuery(); if (result == 1) { cmd.CommandText = "Select @@Identity"; NewPrimaryKeyValue = Convert.ToInt32(cmd.ExecuteScalar()); success = true; } } catch (Exception ex) { HasErrors = true; ExceptionMessage = ex.Message; NewPrimaryKeyValue = -1; success = false; } } } return success;

    } }

Calling the above method . 调用上述方法

You can also validate column names using the following (still keeping with Customer table)您还可以使用以下方法验证列名(仍与客户表保持一致)

SELECT ORDINAL_POSITION, 
       COLUMN_NAME, 
       DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customer'
      AND TABLE_SCHEMA = 'dbo';

Results结果

1,id,int
2,FirstName,nvarchar
3,LastName,nvarchar
4,Address,nvarchar
5,City,nvarchar
6,State,nvarchar
7,ZipCode,nvarchar
8,AccountNumber,nvarchar
9,JoinDate,datetime2

Edit编辑

Another option is to create a class which represents data to be inserted eg另一种选择是创建一个 class 代表要插入的数据,例如

public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
    public string AccountNumber { get; set; }
    public DateTime? JoinDate { get; set; }

}

Then here we use the values passed.然后在这里我们使用传递的值。 Note, in this version cmd.Parameters.AddWithValue is replaced with cmd.Parameters.Add and the query to get the new primary key is appended after the INSERT INTO separated by a semi-colon.请注意,在此版本中,cmd.Parameters.AddWithValue 被 cmd.Parameters.Add 替换,获取新主键的查询附加在 INSERT INTO 之后,以分号分隔。

To call create an instance of the Customer class, populate properties and call the method.要调用创建客户 class 的实例,填充属性并调用方法。

public bool AddCustomer(Customer customer)
{
    bool success = false;

    using (var cn = new SqlConnection { ConnectionString = ConnectionString })
    {
        using (var cmd = new SqlCommand { Connection = cn })
        {
            cmd.CommandText =
                "INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) " + // insert
                "VALUES (@FirstName,@LastName,@Address,@City,@State,@ZipCode);" +             // insert
                "SELECT CAST(scope_identity() AS int);";                                      // get new primary key

            try
            {
                cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar))
                    .Value = customer.FirstName;
                
                cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar))
                    .Value = customer.LastName;
                
                cmd.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar))
                    .Value = customer.Address;
                
                cmd.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar))
                    .Value = customer.City;
                
                cmd.Parameters.Add(new SqlParameter("@State", SqlDbType.NVarChar))
                    .Value = customer.State;
                
                cmd.Parameters.Add(new SqlParameter("@ZipCode", SqlDbType.NVarChar))
                    .Value = customer.ZipCode;

                cn.Open();

                customer.Id = Convert.ToInt32(cmd.ExecuteScalar());
                success = true;

            }
            catch (Exception ex)
            {
                HasErrors = true;
                ExceptionMessage = ex.Message;
                customer.Id = -1;
                success = false;
            }
        }
    }

    return success;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM