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 - 列名无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)