我正在创建一个简单的新闻系统,用户可以在其中撰写新闻报道,并添加图片。
我知道我需要做的'逻辑':
将图像详细信息保存在数据库中,并获取INSERTed时使用的ID
保存新闻报道以及上面的图片ID
如何使用在tblPic中将{pic}插入newsPicID
字段时使用的ID填充tblNews中的picID
字段?
我的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 :(得分: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