验证数据库中是否存在Student id [英] Validating whether Student id is there or not in the database

查看:167
本文介绍了验证数据库中是否存在Student id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下;

My code as follows;

private SqlDataCon SCon = new SqlDataCon();
private SqlCommand cmd;

  SCon.Con.Open();
string str = "Select  count(*)  from Studdet where studid = '" + txt_Studid.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(str, SCon.Con);
int count = (int)cmd.ExecuteScalar();
if (count > 0)
{
    Label4.Text = "Correct Student id";
    return;
}
else
{
    Label4.Text = "InCorrect student id is entered";
    return;
}
  SCon.Con.Close();



从上面的代码中我检查数据库中是否存在学生ID。



在数据库记录中如下;


From my above code i am checking whether student id is there or not in the database.

In Database records as follows;

studid

  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  11
  12
  13
  14
  15



在运行模式下如下;


In run mode as follows;

Student id   Textbox1      Show(button)



i在文本框1中输入学生ID并单击显示按钮,



如果学生ID在数据库中显示消息显示正确的学生ID。

如果数据库中没有学生ID消息显示输入了错误的学生ID。





但是当我输入正确的学生ID并单击显示按钮消息显示输入错误的学生ID。



我上面代码中的问题是什么。我怎么能用c sharp。

请帮帮我。



注意它是网络应用程序。


i enter the student id in the textbox1 and click the show button,

if student id is there in the database message shows Correct Student id.
if student id is not there in the database message shows InCorrect student id is entered.


But when i enter the correct student id and click the Show button message shows InCorrect student id is entered.

what is the problem in my above code. how can i do using c sharp.
please help me.

Note it is web application.

推荐答案

1。 STUDID看起来像是一个数字,而不是一个字符串。因此,不要在查询中将撇号放在STUDID周围。



2.如果表名为STUDENT,那么您需要将查询更正为从STUDENT而不是STUDDET中选择。



3. .Text 属性已经是一个字符串。您不必使用 .ToString()



4.最好使用 SQLParameter 而不是查询的连接字符串。这可以防止SQL注入攻击,你不必担心字符串中嵌入的撇号。



5.使用是个好主意。检索 .Text 属性时修剪以消除开头和结尾的任何空格。



示例:
1. STUDID looks like it is a number and not a string. Therefore, do not put apostrophe around STUDID in the query.

2. If the table is named STUDENT, then you need to correct your query to SELECT from STUDENT instead of STUDDET.

3. The .Text property is already a string. You do not have to use .ToString().

4. It is better to use SQLParameter rather than a concatenated string for your query. That prevents SQL Injection Attacks and you do not have to worry about apostrophes embedded in strings.

5. It is a good idea to use .Trim when retrieving .Text properties to eliminate any spaces at the beginning and the end.

Example:
string str = "Select count(*) from Student where studid=@studid;";
SqlCommand cmd = new SqlCommand(str, SCon.Con);
cmd.Parameters.AddWithValue("studid", (int)txt_Studid.Text.Trim);
int count = (int)cmd.ExecuteScalar();


这篇关于验证数据库中是否存在Student id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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