Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

Invalid column name while using C# for SQL Server

This is my code in 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. 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.

Any help appreciated thank you!

Here is the image of the table I created

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();
        }
    }
}
question from:https://stackoverflow.com/questions/65865540/invalid-column-name-while-using-c-sharp-for-sql-server

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your insert statement is incorrect. 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:

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)";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...