sql - C# insert statement -
sql - C# insert statement -
i kinda new c# , .net applications. work visual studio , have table :
create table [dbo].[table] ( [id] int not null, [meno] nvarchar (50) null, [datum] datetime null, [cas] int null, primary key clustered ([id] asc) );
and have simple insert
public void nahrajskore(string cas) { using (var con = new sqlconnection(cns)) { con.open(); var inset = new sqlcommand("insert table values(@name,@date,@res)", con); inset.parameters.add("@name", sqldbtype.varchar); inset.parameters.add("@date", sqldbtype.datetime); inset.parameters.add("@res", sqldbtype.int); inset.parameters["@name"].value = _hrac.menohraca; inset.parameters["@date"].value = datetime.today; inset.parameters["@res"].value = int.parse(cas); inset.executenonquery(); } }
but method gives me error :
incorrect syntax near keyword 'table'
what doing wrong ?
table
reserved keyword in t-sql.
you should utilize square brackets [table]
if reserved word in use, can avoid error messages surrounding each occurrence of word brackets ([ ]
). however, best solution alter name nonreserved word.
you can utilize using
statement sqlcommand
, can define , add together values of parameters in single line like;
using (var con = new sqlconnection(cns)) { using(var inset = new sqlcommand("insert [table] values(@name,@date,@res)", con)) { inset.parameters.add("@name", sqldbtype.varchar).value = hrac.menohraca; inset.parameters.add("@date", sqldbtype.datetime).value = datetime.today; inset.parameters.add("@res", sqldbtype.int).value = int.parse(cas); con.open(); inset.executenonquery(); } }
also specifying column names in sqlcommand
recommended like;
"insert [table](namecolumn, datecolumn, rescolumn) values(@name,@date,@res)"
c# sql sql-server sql-insert
Comments
Post a Comment