如何创建SQL查询这需要从参数中的URL asp.net C# [英] How can I create SQL Query which Takes Parameters from URL in asp.net C#

查看:169
本文介绍了如何创建SQL查询这需要从参数中的URL asp.net C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的链接是像

http://localhost/default.aspx?phone=9057897874&order=124556

这是我的基本页面传递参数在URL从ASP.net

Here Is my basic Page for passing Parameter In URL from ASP.net

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"     Inherits="WebApplication2._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>Untitled Page</title>
</head>
<body>
<form method="get" action="default.aspx">

<label>Phone No</label>
<input type="text" name="phone" />
<br />
<label>Order No</label>
<input type="text" name="order" />
<br />
<input type="submit" value="submit" />
<br />
</form>


我的C#文件,我可以存储在变量的prameters

my c# file where I can store the prameters in Variables

namespace WebApplication2
 {
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strQuery;

        string phone = Request.QueryString["phone"];
        if (phone != null)
        {
            Response.Write("phone no is ");
            Response.Write(phone);
        }
        else

        {
            Response.Write("You phone number is not correct");
        }

        string order_no = Request.QueryString["order"];
        if (order_no != null)
        {
            Response.Write("Order No is ");
            Response.Write(order_no);
        }
        else
        {
            Response.Write("You Order number is not correct");
        }

//How I can Connect to Mysql Server

        strQuery = "SELECT order_status where orde01=''" + order_no + "'' and phone01=''" + phone + "''";

        Response.Write(strQuery);
}
}

我试图做这样的事情,但它只是给我整个查询的字符串。
我是新上的这个话题。
任何帮助将AP preciate
谢谢

I'm trying to doing something like this but it's only give me whole query as string. I am new on this topic. Any help will be appreciate Thanks

推荐答案

首先,基于串联输入,用户可以改变,特别是当被存储为一个字符串是如何创建的SQL注入漏洞的SQL语句。不要成为那个人。

First off, concatenating a sql statement based on input that the user can change, especially when stored as a string is how SQL Injection Vulnerabilities are created. Don't be that guy.

作为tokenalizing您的查询字符串,命名参数。假设这是你的查询字符串

as for tokenalizing your query string, use named parameters. assume this is your query string

?orderid=777&phone=777-777-7777

Response.QueryString["orderid"] 

将返回777以及

would return '777' and

Response.QueryString["phone"] 

woudl回报777-777-7777

woudl return '777-777-7777'

为您的SQL注入的问题,你有几个选择。一个是参数化的SQL语句,在这里看到的C#示例:的http://罗塞塔code。组织/维基/ Parametrized_SQL_statement
或使用存储过程的参数。最不可取的,但可接受的最低的选择是严格的正则表达式验证您的输入参数,尤其是杀字符,例如'=;。% - 和其他几个人

as for your sql injection issue, you have a couple options. one is a parameterized sql statement, see the C# example here: http://rosettacode.org/wiki/Parametrized_SQL_statement or use a stored procedure with parameters. the least desirable but minimally acceptable option is to regex validate your input parameters strictly, especially killing characters like '=;% -- and a few others.

编辑:现在,我已经有一段时间,逐步建立一个样品,检查了这一点。此示例需要进行定制,以你的数据库,但其对我的MySQL数据库有一个测试表的工作。你将需要安装 MySQLConnector 组和添加项目引用到MySql.Data '在$ C之前$ C将正确编译。

now that I've had some time to work up a sample, check this out. This sample needs to be customized to your database, but its working on my mysql DB with a test table. you will need to install the MySQLConnector pack and add a project reference to 'MySql.Data' before the code will compile correctly.

namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) {
            //define some regex patterns for validating our data.
            const string PHONEREGEX = @"((\(\d{3}\))|(\d{3}-))\d{3}-\d{4}";
            const string ORDERNUMREGEX = @"\d*";

            bool isValid = true;

            string phone = Request.QueryString["phone"]; //read phone from querystring.

            //validate that arg was provided, and matches our regular expression. this means it contains only numbers and single hyphens
            if(!string.IsNullOrWhiteSpace(phone) && System.Text.RegularExpressions.Regex.IsMatch(phone, PHONEREGEX)){
                Response.Write(HttpUtility.HtmlEncode(string.Format("The phone number is {0}", phone))); //HTML Encode the value before output, to prevent any toxic markup.
            } else {
                Response.Write("Phone number not provided.");
                isValid = false;
            }

            string orderStr = Request.QueryString["order"]; //read ordernum from querystring
            long order = long.MinValue;

            //validate that order was provided and matches the regex meaning it is only numbers. then it parses the value into 'long order'.
            if(!string.IsNullOrWhiteSpace(orderStr) && System.Text.RegularExpressions.Regex.IsMatch(orderStr, ORDERNUMREGEX) && long.TryParse(orderStr, out order)){
                Response.Write(HttpUtility.HtmlEncode(string.Format("The order number is {0}", order))); //use 'long order' instead of orderStr.
            } else {
                Response.Write("Order number not provided.");
                isValid = false;
            }

            //if all arguments are valid, query the DB.
            if (isValid) {
                Response.Write(GetOrderStatus( phone, order));
            }

        }

        private static string GetOrderStatus(string phone, long order) {
            string status = "";

            //create a connection object
            string connstring = "SERVER=<YOUR MYSQL SERVER>;DATABASE=<YOUR DATABASE>;UID=<YOUR USER>;PASSWORD=<YOUR PASSWORD>-";//this is a connection string for mysql. customize it to your needs.
            MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connstring); //put your connection string in this constructor call 

            //create a SQL command object
            using (MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand()) { //use a using clause so resources are always released when done.
                cmd.Connection = conn;
                cmd.CommandText = "SELECT `Order_Status` FROM `<YOUR TABLE>` WHERE `Order` = @order AND `Phone` = @phone"; //this needs a From statement 

                //add parameters for your command. they fill in the @order and @phone in the sql statement above. customize these to match the data types in your database.
                cmd.Parameters.Add("order", MySql.Data.MySqlClient.MySqlDbType.Int64,11).Value = order; //do not use @ sign in parameter name
                cmd.Parameters.Add("phone", MySql.Data.MySqlClient.MySqlDbType.VarChar, 50).Value = phone;

                //execute the command, read the results from the query.
                cmd.Connection.Open();
                using (MySql.Data.MySqlClient.MySqlDataReader reader = cmd.ExecuteReader()) {
                    while (reader.Read()) {
                        status = reader.GetString("Order_Status");
                    }
                    cmd.Connection.Close();
                }

            }
            return status;
        }
    }
}

这篇关于如何创建SQL查询这需要从参数中的URL asp.net C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆