2013-05-15 47 views
1

我有兩個通過外鍵鏈接的postgreSQL表。 我想在第二個表中插入來自第一個表主鍵的數據。 我寫在我的C#應用​​程序:使用c插入到postgresql表中#

command1.CommandText = "CREATE TABLE table1(ID CHAR(256) CONSTRAINT id PRIMARY KEY, Title CHAR)"; 
command1.ExecuteNonQuery(); 
command1.CommandText = "insert into projects (ID, Title)" + "values(@id, @title);"; 
command1.Parameters.AddWithValue("@id", ID); 
command1.Parameters.AddWithValue("@title",Title); 
command1.ExecuteNonQuery(); 

對於第二個表:

command2.CommandText = "CREATE TABLE table2(table1id CHAR(256), champs1 CHAR(256), foreign key (table1id) references table1(ID))"; 
command2.ExecuteNonQuery(); 

的問題是,我不知道如何在表2中的第一列是主鍵插入第一張桌子。

對此有何想法? 謝謝你的幫助:)

+2

當你想插入第二個表中的值 –

回答

0

嘗試添加下面的代碼。

cmd3=new SqlCommand("insert into table2 values(@table1id,@champs1,@table1id2)",conn); 
cmd3.parameter.AddWithValue("@table1id",ID);//ID=ID of first table 
cmd3.parameter.AddWithValue("@champs1",chaps); 
cmd3.parameter.AddWithValue("@table1id2",ID);//ID=ID of first table 
cmd3.ExecuteNonQuery(); 

希望它的幫助。

相關問題