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


- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01