我創建SQL Server Management Studio中的表使用此代碼:C#:SQL Server查詢問題
CREATE TABLE contact(
ID INT IDENTITY NOT NULL,
FIRSTNAME VARCHAR(100),
LASTNAME VARCHAR(100)
)
,並在C#中我用這個代碼:
SqlConnection sc = new SqlConnection("Data Source=.\\SQLSERVER; Initial Catalog=BOSS; Integrated Security=TRUE");
SqlDataAdapter sd = new SqlDataAdapter();
sd.InsertCommand = new SqlCommand("INSERT INTO contact VALUES(@ID, @FIRSTNAME, @LASTNAME)");
sd.InsertCommand.Parameters.Add("@ID", SqlDbType.Int).Value = textBox1.Text;
sd.InsertCommand.Parameters.Add("@FIRSTNAME", SqlDbType.VarChar).Value = textBox2.Text;
sd.InsertCommand.Parameters.Add("@LASTNAME", SqlDbType.VarChar).Value = textBox3.Text;
sc.Open();
sd.InsertCommand.ExecuteNonQuery();
sc.Close();
,但是當我添加值到數據庫中,我得到的錯誤:
"ExecuteNonQuery: Connection property has not been initialized"
,我加入sc
給我的第一insertcommand
固定它,但是當我運行程序我得到另一個錯誤:
An explicit value for the identity column in table 'contact' can only be specified when a column list is used and IDENTITY_INSERT is ON.
您應該將連接創建封裝在'using'語句中。 – Oded
您沒有將DataAdapter連接到連接 –
爲什麼直接使用'DataAdapter'而不是'Command'? – Oded