简体   繁体   中英

Using a SQL Server Stored Procedure in Visual Studio

My Experience & What I'm Using

So I'm just starting off with a very basic web application in ASP.NET to gain a little more familiarity with SQL Server Management Studios and Visual Studios 2010. Normally, I use MySQL, PHP, and Sublime Text Editor 2. I'm not very experienced with C# and implementing a database in Visual Studios. So I'm trying to use a stored procedure from SQL Server Management Studios and implement it in Visual Studios 2010.

The Issue

So here's my problem: I'm trying to create a basic webpage that links to a SQL Server and be able to add, delete, search and display all records from the database. Now I've written my own code based on what I thought was correct for add/delete and nothing happens when I click the buttons. So I'm sure you can see where my frustration derives from. I'm not sure if the issue is in my C# coding or in my SQL coding.

I'd like to focus on just getting my add/delete buttons to work and then to figure out the logic to display all files. I'd like to be able to click a button and then have it show all files instead of just displaying a grid. My database is called FirstApp.

Here's what's in my web.config file:

<add name="FirstApp" connectionString="Data Source=PCNAME\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True"
  providerName="System.Data.SqlClient" />

Now this is what's in my Default.aspx.cs file:

* CORRECT CODE NOW! *

  namespace FirstApp
  {
  public partial class _Default : System.Web.UI.Page
  {
  public string CommandArgument { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void MessageBox(string msg)
    {
        Label lbl = new Label();
        lbl.Text = "<script language='javascript'>" + Environment.NewLine +  "window.alert('" + msg + "')</script>";
        Page.Controls.Add(lbl);
    }

    //Add a new company to the database
    protected void add_Click(object sender, EventArgs e)
    {
        SqlDataReader rdr = null;
        string connectionString = null;
        SqlConnection cnn;
        connectionString = "Data Source=ITXDK29M91\\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True";
        cnn = new SqlConnection(connectionString);
        try
        {
            cnn.Open();
            SqlCommand cmd = new SqlCommand("dbo.Add_Company", cnn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@companyname", companyname.Text);
            cmd.Parameters.AddWithValue("@companyphone", companyphone.Text);
            cmd.Parameters.AddWithValue("@companyid", companyid.Text);
            cmd.Parameters.AddWithValue("@companytype", companytype.Text);
            rdr = cmd.ExecuteReader();
         }
        finally
        {

            //Close the connections 
            if (cnn != null)
            {
                cnn.Close();
            }
            if (rdr != null)
            {
                rdr.Close();
            }
        }
     }

     //Delete a company from the database
     protected void delete_Click(object sender, EventArgs e)
     {
         SqlDataReader rdr = null;
        SqlConnection cnn;
        string connectionString = null;
        connectionString = "Data Source=ITXDK29M91\\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True";
        cnn = new SqlConnection(connectionString);
        try
        {
            cnn.Open();
            SqlCommand cmd = new SqlCommand("dbo.deleteCo", cnn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@ID", SqlDbType.Int);
            rdr = cmd.ExecuteReader();

        }

        finally
        {

            //Close the connections 
            if (cnn != null)
            {
                cnn.Close();
            }
            if (rdr != null)
            {
                rdr.Close();
            }
        }
    }


    protected void Search_Click(object sender, EventArgs e)
    {

    }

    protected void Getall_Click(object sender, EventArgs e)
    {

    }

  }
  }

This is what's in my Source Code in Default.aspx

 <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">      <h2>Ready for an Adventure? Let&#39;s get started! 
     </h2> <hr />This is where you can enter information about your company. 
 <br />
 <form method="post" action="">
Company Name:<br /> 
<asp:TextBox ID="companyname" runat="server"></asp:TextBox>
<br />
Company Phone Number:<br />
<asp:TextBox ID="companyphone" runat="server"></asp:TextBox>
<br />
Company Tax ID Number:
<br />
<asp:TextBox ID="companyid" runat="server"></asp:TextBox>
<br />
Type of business: <br />
     <asp:TextBox ID="companytype" runat="server"></asp:TextBox>
<br />
 <asp:Button ID="add" runat="server" BackColor="DeepSkyBlue" 
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" 
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White" 
onclick="add_Click" Text="Submit" Width="128px" />
</form> <hr /> 
Want to delete your company information?<br />
Enter in the Company ID Number:&nbsp;
<br />
 <asp:TextBox ID="PrimaryKey" runat="server" Width="120px"></asp:TextBox>
 <br />
 <asp:Button ID="delete" runat="server" BackColor="DeepSkyBlue" 
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" 
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White" 
onclick="delete_Click" Text="Delete Info" Width="119px" />
<br />
<hr /> 
Looking for similar companies?
<br />
(Ex: Retail, Designer, Restaurant, etc.) &nbsp;
<br />
Enter the type of company:
 <br />
 <asp:TextBox ID="scompanyid" runat="server" Width="120px"></asp:TextBox>
 <br />
 <asp:Button ID="Search" runat="server" BackColor="DeepSkyBlue" 
 BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" 
 CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White" 
 onclick="Search_Click" Text="Start Searching!" Width="119px" />
 <br />
 <hr /> 
   Want to see all the companies that we work with? <br /> 
   Click the button below! 
 <br />
 <asp:Button ID="Getall" runat="server" BackColor="DeepSkyBlue" 
 BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" 
 CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White" 
 onclick="Getall_Click" Text="Get all records!" Width="119px" />
 <br />
   <br />
   </asp:Content>

UPDATE: I've updated the code to display the correct code. The add button works but my delete button is not. I'm still trying to figure that one out.

You're not actually opening a connection or executing your SQL commands. Generally, the way you execute a simple command is:

using (var conn = new SqlConnection(connectionString))
{
    using (var comm = conn.CreateCommand())
    {
        conn.Open();
        comm.CommandText = "SOME SQL HERE";

        // command type, parameters, etc.

        //pick one of the following
        comm.ExecuteNonQuery();
        int value = (int)comm.ExecuteScalar();
        SqlDataReader reader = comm.ExecuteReader();

    }
}

You need to actually execute the command. There are four types of execution (depending on the type of results you'll be expecting from your query statement)

  • ExecuteReader - Rows and columns returned (eg Normal select queries)
  • ExecuteNonquery - No results expected. (eg Deleting a record)
  • ExecuteScalar - Single value (eg Count, Max, etc..)
  • ExecuteXMLReader - For XML stuff

Something like this for the add

cmd.ExecuteNonquery();

Even before worrying about executing the command though, you always need an open connection through which you execute commands and you need to link your command to it:

SqlConnection cn = new SqlConnection(connStr);
cn.Command = cmd;
cn.Open();
<your command/parameter code here>
cmd.ExecuteNonquery();

And don't forget to put stuff back the way you found it:

cmd.Close();
cn.Close();

There are other suggestions I'd make--like making the phone number varchar since you're not going to do arithmetic on it as a number--but this is not your real question here and now.

Best wishes!

FYI: Side topic: Whenever you begin to use commands to return results, you will not need a "new" for your SqlDataReaders because commands executed with ExecuteReader create and return an SqlDataReader object. This means you can just do this

//This next line not needed
//dr = new SqlDataReader()   
SqlDataReader dr = cmd.ExecuteReader();

It looks like you aren't executing your SQL statements. Try creating a method that does the below then call that method from your delete button click event.

    public static void DeleteSomething()
    {
        using (var conn = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand("usp_proc_delete", conn.CreateCommand()))
            {
                 conn.Open()
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.Parameters.AddWithValue("@PrimaryKey", SqlDbType.Int);
                 cmd.ExecuteNonQuery();
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM