我想根据用户输入C#SQL从数据库中选择问题 [英] I want to select questions from the database on basis of user input C# SQL

查看:124
本文介绍了我想根据用户输入C#SQL从数据库中选择问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有问题,用户从组合框中选择一个他想参加测验的主题



我尝试过:



i have questions in database and user selects a subject from combo box in which he wants to take quiz

What I have tried:

<pre> private void IndexChanged(object sender, EventArgs e)
        
               
                {
           

        
       
        
            SqlConnection conn = new SqlConnection();
            string cmdText = "SELECT Top " + textB.Text + " * from Ques where Sub='" + combo.Text + "' ORDERBY newid()";

它只是在2 4附近说错误等我在文本框中放置的值以显示没有问题.. idk我的查询或我的逻辑出错了...需要帮助而不是

its just say error near 2 4 etc the values i put in textbox to display no of questions .. idk whats going wrong my query or my logic .. help needed thanx

推荐答案

不是你的解决方案问题,但你有另一个问题。

Not a solution to your question, but another problem you have.
string cmdText = "SELECT Top '" + textBox1.Text + "'Question,Opt1,Opt2,Opt3,Opt4 from Questions where SubName='" + comboBox1.Text + "' ORDERBY newid()";



永远不要通过与用户输入连接来构建SQL查询,它被命名为SQL注入,这对你的数据库很危险并且容易出错。

一个名字中的单引号和你的程序崩溃。如果像Brian O'Conner这样的用户输入可能会使您的应用程序崩溃,那么这是一个SQL注入漏洞。

SQL注入 - 维基百科 [ ^ ]

SQL注入 [ ^ ]


Never build an SQL query by concatenating with user inputs, it is named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability.
SQL injection - Wikipedia[^]
SQL Injection[^]

Quote:

它只是说2 4等附近的错误我在文本框中放置的值以显示没有问题

its just say error near 2 4 etc the values i put in textbox to display no of questions



使用有问题的 cmdText的内容改进您的问题,所以我们可以知道什么是真正的查询。


Improve your question with the content of the offending cmdText, so we can know what is the real query.


在行上放置一个断点
string cmdText = "SELECT Top '" + textBox1.Text + "'Question,Opt1,Opt2,Opt3,Opt4 from Questions where SubName='" + comboBox1.Text + "' ORDERBY NEWID()"; // i did tat paremetrized query thing here

跨过那一行并输入

? cmdText

在Visual Studio的即时窗口中。您应该看到

in the immediate window of Visual studio. You should see

SELECT Top '10'Question,Opt1,Opt2,Opt3,Opt4 from Questions where SubName='xxxxxx' ORDERBY NEWID()

显然 10 xxxxx 将被文本框中的任何内容替换。



看上去很长很难 Top'10'Question



也许如果说十大问题它可能有用吗?

Obviously 10 and xxxxxwill be replace by whatever you have in your textboxes.

Look long and hard at Top '10'Question

Perhaps if that said Top 10 Question it might work?


这篇关于我想根据用户输入C#SQL从数据库中选择问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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