问题描述
正如你们中的一些人可能从我之前的帖子中看到的那样,我是使用 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 - 列名无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!