从 WPF 执行存储过程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12834249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:44:00  来源:igfitidea点击:

Execute stored procedure from WPF

c#sqlwpfstored-procedures

提问by nlakumar

I am doing a simple wpf application of registration process. The registration details given by user must be stored in server. I want to use a stored procedure for this. I am using SQL server 2008. I created the table and stored procedure in server for storing the input from user. I am not able to use it in my wpf app. The following is C# code.

我正在做一个简单的wpf申请注册过程。用户提供的注册详细信息必须存储在服务器中。我想为此使用存储过程。我正在使用 SQL Server 2008。我在服务器中创建了表和存储过程,用于存储来自用户的输入。我无法在我的 wpf 应用程序中使用它。以下是C#代码。

Registration.xaml.cs:

注册.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Data; 

namespace storedprocedure
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class Registration : Window
{
    public Registration()
    {
        InitializeComponent();
    }
private void Login_Click(object sender, RoutedEventArgs e)
    {

        Login login = new Login();

        login.Show();

        Close();

    }



    private void button2_Click(object sender, RoutedEventArgs e)
    {

        Reset();

    }



    public void Reset()
    {

        textBoxFirstName.Text = "";

        textBoxLastName.Text = "";

        textBoxEmail.Text = "";

        textBoxAddress.Text = "";

        passwordBox1.Password = "";

        passwordBoxConfirm.Password = "";

    }

    private void button3_Click(object sender, RoutedEventArgs e)
    {

        Close();

    }



    private void Submit_Click(object sender, RoutedEventArgs e)
    {

        if (textBoxEmail.Text.Length == 0)
        {

            errormessage.Text = "Enter an email.";

            textBoxEmail.Focus();

        }

        else if (!Regex.IsMatch(textBoxEmail.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
        {

            errormessage.Text = "Enter a valid email.";

            textBoxEmail.Select(0, textBoxEmail.Text.Length);

            textBoxEmail.Focus();

        }

        else
        {

            string firstname = textBoxFirstName.Text;

            string lastname = textBoxLastName.Text;

            string email = textBoxEmail.Text;

            string password = passwordBox1.Password;

            if (passwordBox1.Password.Length == 0)
            {

                errormessage.Text = "Enter password.";

                passwordBox1.Focus();

            }

            else if (passwordBoxConfirm.Password.Length == 0)
            {

                errormessage.Text = "Enter Confirm password.";

                passwordBoxConfirm.Focus();

            }

            else if (passwordBox1.Password != passwordBoxConfirm.Password)
            {

                errormessage.Text = "Confirm password must be same as password.";

                passwordBoxConfirm.Focus();

            }

            else
            {

                errormessage.Text = "";

                string address = textBoxAddress.Text;

                SqlConnection con = new SqlConnection("Data Source=DBSERVER\DUBAIAIRPORT;Initial Catalog=LoginWPF;User ID=sa;Password=sa");


    con.Open(); 

    using (SqlCommand cmd = new SqlCommand("storedprocedure", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.ExecuteNonQuery(); 
    }

    con.Close();
}






            }
        }
    }

}

Below is the stored procedure created in my sql server database

下面是在我的 sql server 数据库中创建的存储过程

CREATE PROCEDURE submitdata
(
 @Firstname varchar(50),
 @Lastname varchar(50),
 @Email varchar(50),
 @Password varchar(50),
 @Address varchar(50)
 )
 AS
 insertinto                                                                              registrationdata(Firstname,Lastname,Email,Password,Address)values(@firstname,@lastname,               @email,@password,@address)

The name of database is storedprocedure. I am using VS 2010 with .net4.0.

数据库的名称是存储过程。我使用 VS 2010 和 .net4.0。

Please help with the c# code i have to insert in Registration.xaml.cs. Thank you.

请帮助我必须在 Registration.xaml.cs 中插入的 c# 代码。谢谢你。

采纳答案by Mohsen Afshin

con.Open(); 

using (SqlCommand cmd = new SqlCommand("submitdata", con))
{
    cmd.CommandType = CommandType.StoredProcedure;

    SqlParameter param1 = new SqlParameter("@Firstname", SqlDbType.VarChar);
    param1.Value = "my first name";

     // ... the rest params

    cmd.Parameters.Add(param1);

    // cmd.Parameters.Add(param2);....

    cmd.ExecuteNonQuery(); 
}

con.Close();

回答by Adriano Repetti

First few questions
What did you try to do? Do you have a database connection? What kind of technology you're using to access your data layer (LINQ to something? Entities? No abstraction at all?)

前几个问题
你试图做什么?你有数据库连接吗?你使用什么样的技术来访问你的数据层(LINQ to something?实体?根本没有抽象?)

You should post your actual code too.

您也应该发布您的实际代码。

Code example
Anyway here a small code example to explain how to execute a stored procedure using plain System.Data.SqlClientclasses.

代码示例
无论如何,这里有一个小代码示例来解释如何使用普通System.Data.SqlClient类执行存储过程。

private static void SubmitData(string firstName, string lastName)
{
    using (var connection = new SqlConnection("your connection string"))
    {
        connection.Open();

        using (var command = connection.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "submitdata";

            command.Parameters.AddWithValue("@FirstName", firstName);
            command.Parameters.AddWithValue("@LastName", lastName);

            command.ExecuteNonQuery();
        }
    }
}

回答by Matthew Kennedy

If you connect to the database in the Visual Studio server explorer, and create a LINQ to SQL classes you will never have to touch SqlCommand. Your stored procedure will be generated as a method that you can call.

如果您在 Visual Studio 服务器资源管理器中连接到数据库,并创建一个 LINQ to SQL 类,您将永远不必接触SqlCommand. 您的存储过程将生成为您可以调用的方法。

http://msdn.microsoft.com/en-us/library/bb386976.aspx

http://msdn.microsoft.com/en-us/library/bb386976.aspx