sql - Error while inserting into database c# -
there no error clarification
i trying insert table called "test" has 1 column, primary key called "id". new using databases in visual studio , think there wrong insert syntax since other functions work fine. general layout this?
using (sqlcommand command = new sqlcommand("insert test (id) values(1)", conn))
overall code looks this:
class program { static void main(string[] args) { string connection = "data source=.\\sqlexpress;" + "user instance=true;" + "integrated security=true;" + "attachdbfilename=|datadirectory|haythamservice.mdf;"; try { using (sqlconnection conn = new sqlconnection(connection)) { conn.open(); using (sqlcommand command = new sqlcommand("insert test (id) values(1)", conn)) { command.executenonquery(); using (sqldatareader reader = command.executereader()) { while (reader.read()) { (int = 0; < reader.fieldcount; i++) { console.writeline(reader.getvalue(i)); } console.writeline(); console.read(); } } } conn.close(); } } catch (exception ex) { } } }
first of all: swallowing exception not help. remove try-catch-block , let application run error - you'll see problem is.
secondly: you're executing insert command using executenonquery
, right after try read using sqldatareader
? kind of output expect that?
probably, if id
primary key column, cause of primary key violation error, because you're executing same insert twice using same value - , not allowed primary key.
to put short: create second command executereader
. command should read select * test
.
thirdly: use sqlconnectionstringbuilder
class create connection string instead of hardcoding it. against invalid connection strings.
Comments
Post a Comment