SQL INSERT-无效的列名 [英] SQL INSERT - Invalid column name
问题描述
从我以前的文章中可能看到,我是使用C#创建网站的新手(尽管我对Windows Forms应用程序使用C#有相当的经验).强大的功能吸引了我远离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!)
谢谢
Tripbrock
Tripbrock
推荐答案
列名后面缺少括号,该值表示字符串,因此必须用引号引起来:
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-无效的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!