You are here: Re: INSER at runtime? « MsSQL Server « IT news, forums, messages
Re: INSER at runtime?

Posted by Dan Guzman on 10/02/06 12:06

The reason you are getting the error is because you are passing C# variable
names in the SQL statement and SQL Server has no idea what those are. I
completely agree with Razvan's suggestion to use parameters. You can then
use those parameters in your SQL statement:

sqlcmd.CommandText = "INSERT INTO tblUsers(Username,Password)" +
" VALUES(@UserId, @Password)";

--
Hope this helps.

Dan Guzman
SQL Server MVP

"Krij" <gsb58@start.no> wrote in message
news:1159789120.493746.210990@m73g2000cwd.googlegroups.com...
> Hi!
>
> Can anybody tell me what I'm missing here?
>
> I'm trying to insert a new record into a sql-database from code at
> runtime (not stored procedure),
> but get the following error message:
>
> "The 'strUn' is not permitted in this context.
> Only constants, expressions or variables allowed here.
> Column names are not permitted."
>
> //Create sql connection
> SqlConnection con = new SqlConnection
> ("server=LocalHost;database=Users;uid=geir;pwd=geir");
>
> //Open database connection
> con.Open();
>
> //Create variables to hold values from textboxes
> string strUn = txtUsername.Text;
> string strPw = txtPassword.Text;
>
> //Create a sqlCommand to insert textbox values into sql-database
> SqlCommand sqlcmd = new SqlCommand();
> sqlcmd.CommandText = "INSERT INTO tblUsers(Username,Password)
> VALUES(strUn, strPw)";
> sqlcmd.Connection = con;
>
> try
> {
> sqlcmd.ExecuteNonQuery();
> }
> catch(SqlException ex)
> {
> lblInfo.Text = "ExecuteNonQuery failed because: \n" +
> "\n" +
> ex.Message;
> }
> finally
> {
> con.Close();
> }
>

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация