我想从textbox1.text中获取sql列F_Name的数据,如果在texbox1中匹配F_Name(在快速三个章程中)匹配,则在网格视图中显示数据 [英] i want to campare data of sql column F_Name from textbox1.text and if in texbox1 3 charater that match in F_Name(in fast three charter) match then show data in grid view

查看:90
本文介绍了我想从textbox1.text中获取sql列F_Name的数据,如果在texbox1中匹配F_Name(在快速三个章程中)匹配,则在网格视图中显示数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void textBox1_KeyUp(object sender, KeyEventArgs e)
       {
           len = Convert.ToInt32(textBox1.Text.Length);
           string str = "select SUBSTRING(F_Name,1,len) from Opd_Detail where F_name like'" + textBox1.Text + "'";
           textBox2.Text = str;
           c.con_open();
           SqlDataAdapter sda = new SqlDataAdapter(str, Con_Class.con);
           DataTable dt = new DataTable();
           sda.Fill(dt);
           dataGridView1.DataSource = dt;
           c.con_close();
       }



(错误是len的尾部)


(error is tail in len)

推荐答案

嗯,是的。它将是:

Well, yes. It would be:
len = Convert.ToInt32(textBox1.Text.Length);
 string str = "select SUBSTRING(F_Name,1,len) from Opd_Detail where F_name like'" + textBox1.Text + "'";



len 在你的SQL语句中是字符串的一部分,所以字符'l',' e'和'n'被传递给SQL,而不是上面一行中 len 变量的值。

有两种方法可以修复它:

1)添加值而不是名称:


len in your SQL statement is part of a string, so the characters 'l', 'e', and 'n' are passed to SQL, not the value of the len variable in the line above.
There are two ways to fix it:
1) Add the value instead of the name:

len = Convert.ToInt32(textBox1.Text.Length);
 string str = "select SUBSTRING(F_Name,1," + len + ") from Opd_Detail where F_name like'" + textBox1.Text + "'";

但这是一个坏主意 - 它效率低下,非常危险。

2)将它作为参数添加到SQL查询中 - 同时保护您的数据库!不要连接字符串以构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询:

But that's a bad idea - it's inefficient, and very dangerous.
2) Add it as a parameter to your SQL query - and at the same time protect your database! Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead:

string str = "SELECT SUBSTRING(F_Name,1,@LEN) FROM Opd_Detail FROM F_name like '%' + @COMP + '%'";
System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter(str, Con_Class.con);
sda.SelectCommand.Parameters.AddWithValue("@LEN", textBox1.Text.Length);
sda.SelectCommand.Parameters.AddWithValue("@COMP", textBox1.Text);

您是否意识到LIKE是一个外卡匹配,如果您包含通配符,它​​只会执行任何有用的操作? (对于SQL来说,这是百分比字符)



错别字。[/ edit]

You do realize that LIKE is a wild card match that only does anything useful if you include wildcards? (Which for SQL is a percent character)

[edit]Typos.[/edit]


这篇关于我想从textbox1.text中获取sql列F_Name的数据,如果在texbox1中匹配F_Name(在快速三个章程中)匹配,则在网格视图中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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