當單擊“插入圖書信息”按鈕時,將用戶的信息保存到book_info表中。注意:封面圖片要求先上傳到網(wǎng)站根目錄下的“upload”文件夾中,再將圖片在網(wǎng)站中的相對路徑保存到數(shù)據(jù)庫book_info表的Image字段中。
布局代碼:
%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
html xmlns="http://www.w3.org/1999/xhtml">
head runat="server">
title>/title>
/head>
body>
form id="form1" runat="server">
table>
tr>
td>asp:Label ID="Label1" runat="server" Text="書名:">/asp:Label>/td>
td>asp:TextBox ID="TextBox1"
runat="server">/asp:TextBox>
/td>
/tr>
tr>
td>asp:Label ID="Label2" runat="server" Text="作者:">/asp:Label>/td>
td> asp:TextBox ID="TextBox2"
runat="server">/asp:TextBox>/td>
/tr>
tr>
td> asp:Label ID="Label3" runat="server" Text="出版社:">/asp:Label>/td>
td>asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
asp:ListItem>清華大學出版社/asp:ListItem>
asp:ListItem>機械工業(yè)出版社/asp:ListItem>
asp:ListItem>人民郵電出版社/asp:ListItem>
asp:ListItem>電子工業(yè)出版社/asp:ListItem>
/asp:DropDownList>/td>
/tr>
tr>
td>asp:Label ID="Label4" runat="server" Text="出版日期:">/asp:Label>/td>
td>asp:Calendar ID="Calendar1" runat="server">/asp:Calendar>/td>
/tr>
tr>
td>
asp:Label ID="Label5" runat="server" Text="封面圖片:">/asp:Label>/td>
td>
asp:FileUpload ID="FileUpload1" runat="server" />/td>
/tr>
tr>
td>/td>
td>
asp:Button ID="Button1" runat="server" Text="插入圖片信息" onclick="Button1_Click" />/td>
/tr>
/table>
/form>
/body>
/html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string savePath = Server.MapPath("~/images/");
if (FileUpload1.HasFile)
{
String fileName = FileUpload1.FileName;
savePath += fileName;
FileUpload1.SaveAs(savePath);
}
string sql = "Data Source=A25;Initial Catalog=test;Integrated Security=True";
string sqlStr = @"Insert into book_info(Book_name,Author,Press,Press_date,Image) values
('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Text + "','"
+ Calendar1.SelectedDate.ToShortDateString() + "','" + FileUpload1.FileName + "')";
using (SqlConnection conn = new SqlConnection(sql))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sqlStr;
cmd.ExecuteNonQuery();
}
}
Response.Write("插入成功!");
}
}