1、 在數據庫中建立一個test數據庫,在test數據庫中建立一個book_info表。
Book_name varchar(100)
Author varchar(50)
Press varchar(50)
Press_date varchar(20)
Image varchar(30)
2、 制作一個如下頁面:
當單擊“插入圖書信息”按鈕時,將用戶的信息保存到book_info表中。注意:封面圖片要求先上傳到網站根目錄下的“upload”文件夾中,再將圖片在網站中的相對路徑保存到數據庫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>機械工業出版社</asp:ListItem> <asp:ListItem>人民郵電出版社</asp:ListItem> <asp:ListItem>電子工業出版社</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>
cs代碼
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("插入成功!"); } }
以上就是本文的全部內容,希望可以給大家一個啟發,對大家的學習有所幫助。