2016-11-23 103 views
-1

我正在制作一个简单的新闻系统,用户可以在其中写新闻故事,并添加一张照片。我如何从一张桌子上取得身份证件并放置在另一张桌子上?

我所知道的“逻辑”的背后是什么,我需要做的:

  • 保存在数据库中的图像细节,并得到,当它被插入

  • 保存的消息称,被使用的ID故事与图片ID一起我刚刚得到上述

我怎么能填充newsPicID场tblNews与当PIC被插入到被使用的ID picID字段在tblPic?

我的INNER JOIN会看起来像这样吗?

SELECT * FROM tblNews INNER JOIN picTable ON picTable.picID = newsTable.newsPicID 

对于任何引用,这里是我当前的代码:

 if (FileUpload1.PostedFile != null) 
     { 
      string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName); 

      // Save files to disk 
      FileUpload1.SaveAs(Server.MapPath("/images/admin/news/" + FileName)); 

      // Add Entry to DataBase 
      String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString; 

      SqlConnection con = new SqlConnection(strConnString); 
      string strQuery = "insert into tblFiles (FileName, FilePath) values(@FileName, @FilePath); insert into tblNews (newsTitle, newsDate, newsSummmary, newsContent) values(@newsTitle, @newsDate, @newsSummmary, @newsContent)"; 

      SqlCommand cmd = new SqlCommand(strQuery); 
      cmd.Parameters.AddWithValue("@FileName", FileName); 
      cmd.Parameters.AddWithValue("@FilePath", "/images/admin/news/" + FileName); 
      cmd.Parameters.AddWithValue("@newsTitle", txtnewstitle.Text);    
      cmd.Parameters.AddWithValue("@newsDate", txtnewsdate.Text);    
      cmd.Parameters.AddWithValue("@newsSummary", txtnewssummary.Text);    
      cmd.Parameters.AddWithValue("@newsContent", txtnewsmaincontent.Text);    

      cmd.CommandType = CommandType.Text; 
      cmd.Connection = con; 

      try { 
       con.Open(); 
       cmd.ExecuteNonQuery(); 
      } 
      finally { 
       con.Close(); 
       con.Dispose(); 
      } 
     } 
+0

是picID标识字段? –

+0

@Vicky_Thinking是的。 tblFiles中的picID和tblNews中的newsID是主要和标识 – cmp

回答

1

我建议建立一个存储过程来节省,文件和新闻。然后你可以使用一个事务来控制整个操作。

事情与此类似:

create procedure dbo.NewsInsert 
(@FileName varchar(65) 
,@FilePath varchar(300) 
,@newsTitle varchar(100) 
,@newsDate DateTime 
,@newsSummary varchar(100) 
,@newsContent varchar(1024) 
) 
as 
begin 

    begin transaction 

    insert into tblFiles (FileName, FilePath) 
    values(@FileName, @FilePath); 

    if @@ERROR <> 0 
    begin 
     if @@TRANCOUNT > 0 ROLLBACK TRANSACTION 
     -- RAISE SOME ERROR - 
    end 

    -- I spouse tblFiles has some identity field as PICTURE_ID 
    -- use SCOPE_IDENTITY() to get it 

    insert into tblNews (newsTitle, newsDate, newsSummmary, newsContent, PICTURE_ID) 
    values(@newsTitle, @newsDate, @newsSummmary, @newsContent, scope_identity()); 

    if @@ERROR <> 0 
    begin 
     if @@TRANCOUNT > 0 ROLLBACK TRANSACTION 
     -- RAISE SOME ERROR - 
    end 

    -- finally commit the transaction 
    COMMIT TRANSACTION 
end 
+0

谢谢@mcNets!我将读取存储过程并对其进行测试:-)存储过程在这里可以更好地工作吗? – cmp

+0

使用事务可以确保已插入两个记录或none。 – McNets

相关问题