使用asp.net将值插入SQL Server

时间:2015-04-05 05:44:26

标签: mysql asp.net

表单按钮:

<asp:Button ID="Button1" runat="server" Text="GO" onclick="Button1_Click" />

代码背后:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
  1. 将值(生成的id)插入SQL Server数据库的简单代码是什么?触发Button1_Click时,应将生成的ID插入tbl_batch

  2. 我应该向web.config添加任何内容(如数据库连接)吗?

2 个答案:

答案 0 :(得分:1)

您无法在web.config文件中执行CRUD操作,但我使用SqlDataSource有一个简单的解决方案。按照以下步骤操作,以简单的方式让你的事情发生。

连接字符串在我的Web.config中:

<add name="Conn" connectionString="Server=David-PC;Database=DNN711;uid=sa;pwd=sa123;" providerName="System.Data.SqlClient"/>

ASPX加价:

<asp:Button ID="Button1" runat="server" Text="GO" onclick="Button1_Click" />

    <asp:SqlDataSource ID="sdsInsert" runat="server" 
        ConnectionString="<%$ ConnectionStrings:Conn %>" 
        InsertCommand="Insert into tbl_batch (GeneratedID) values (@GeneratedID)"
        InsertCommandType="Text"></asp:SqlDataSource> 

按钮点击活动:

protected void Button1_Click(object sender, EventArgs e)
{
    sdsInsert.InsertParameters.Add("GeneratedID", "123");
    sdsInsert.Insert();
}

如果您有任何疑问,请与我们联系。

答案 1 :(得分:1)

 Using con As SqlConnection = New SqlConnection("Server=localhost\SQLEXPRESS; Database=databasename; User Id=sa; Password=yourpassword;")
            Using cmd As SqlCommand = con.CreateCommand()
                Using da As New SqlDataAdapter
                    con.Open()

                    cmd.CommandText = "insert into ..."
                    da.SelectCommand = cmd
                    Dim dt As New DataTable
                    da.Fill(dt)

                End Using
            End Using
        End Using