SQL INSERT - 列名无效

SQL INSERT - Invalid column name(SQL INSERT - 列名无效)
本文介绍了SQL INSERT - 列名无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

正如你们中的一些人可能从我之前的帖子中看到的那样,我是使用 C# 创建网站的新手(尽管我有相当多的将它用于 Windows 窗体应用程序的经验).强大的力量让我远离 PHP,但我一直在我认为的基础知识上失败.

As some of you may of seen from my previous post I'm new to using C# to create websites (Although I have a fair bit of experience using it for Windows Forms apps). The powers that be are tempting me away from PHP but I keep failing at what I consider the basics.

无论如何,这是我的问题.我正在尝试在 SQL 数据库中创建一个简单的条目.我知道我与数据库的连接很好,因为我可以整天执行 SELECT 查询,但我在使用 Insert 时遇到了问题.

Anyway, this is my issue. I am trying to create a simple entry into a SQL database. I know my connection to the DB is fine as I can reel off SELECT queries all day long but I'm having trouble with using Insert.

这是我的代码:

string filename = "abc123.jpg";
SqlConnection link = new SqlConnection(//you dont need to see my data here ;));
string sqlcode = "INSERT INTO file_uploads (upload_filename VALUES ("+filename+")";
SqlCommand sql = new SqlCommand(sqlcode,link);
link.open();
sql.ExecuteNonQuery();

这会导致 try/catch 返回无效的列名 abc123.jpg".

This results in "Invalid column name abc123.jpg" returned from the try/catch.

任何帮助将不胜感激.(我希望他们能让我在 PHP 中做到这一点,哈哈!)

Any help would be appreciated. (I wish they would let me do this in PHP lol!)

谢谢,

绊脚石

推荐答案

你在列名后面缺少一个括号,值代表一个字符串,因此必须用引号引起来:

You are missing a parenthesis after the column name and the value represents a string and as such must be enclosed in quotes:

string sqlcode = "INSERT INTO file_uploads (upload_filename) " + 
                 "VALUES ('"+filename+"')";

但是,正确的方法是使用参数化查询:

However, the correct way would be to use a parameterized query:

string filename = "abc123.jpg";
SqlConnection link = new SqlConnection(/*you dont need to see my data here ;)*/);
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES (@filename)";
SqlCommand sql = new SqlCommand(sqlcode,link);
sql.Parameters.AddWithValue("@filename", filename);
link.open();
sql.ExecuteNonQuery();

这篇关于SQL INSERT - 列名无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Custom Error Queue Name when using EasyNetQ for RabbitMQ?(使用 EasyNetQ for RabbitMQ 时自定义错误队列名称?)
How to generate password_hash for RabbitMQ Management HTTP API(如何为 RabbitMQ 管理 HTTP API 生成密码哈希)
Rabbitmq Ack or Nack, leaving messages on the queue(Rabbitmq Ack 或 Nack,将消息留在队列中)
Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Specify Publish timeouts in mass transit(指定公共交通中的发布超时)
RabbitMQ asynchronous support(RabbitMQ 异步支持)