如何在C#WPF中将常量sting变量传递给SQL查询 [英] How to pass constant sting variable into SQL query in C# WPF

查看:96
本文介绍了如何在C#WPF中将常量sting变量传递给SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有传递数据,它应该在数据库中



我尝试过:



i试过传递查询请给出解决方案



这里我需要输入paas常量字符串值,如字符串英文=English.Text到数据库

 SqlCeConnection conn = new SqlCeConnection(DBConnection.GetConnString()); 

SqlCeEngine engine = new SqlCeEngine(Common.CommonProperties.ConnString + Common.CommonProperties.Password);
SqlCeCommand cmd;
DataSet ds = new DataSet();
if(textEMail.Text ==|| passwordBox1.Password ==)
{
System.Windows.MessageBox.Show(输入EmailID和密码。);
返回;
}

cmd = new SqlCeCommand(SELECT * FROM Login where Where EmailID ='+ textEMail.Text +'and Password ='+ passwordBox1.Password +',conn );
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);

da.Fill(ds);
int i = ds.Tables [0] .Rows.Count;
if(i == 1)
{
conn.Open();
String q1 =插入LoginTime(LoginDate,EmailID,Medium)值(getdate(),'+ textEMail.Text +','+ Kannada.Text +');
cmd.CommandType = CommandType.Text;

cmd.CommandText = q1;
cmd.ExecuteNonQuery();
System.Windows.MessageBox.Show(你成功登录);

Liststd_KM f2 = new Liststd_KM();
f2.Show();
this.Hide();
//ds.Clear();

}
else
{
System.Windows.MessageBox.Show(未注册用户或无效名称/密码);
passwordBox1.Password =;
}

解决方案

如何在C#WPF中将常量sting变量传递给SQL查询

1我没有传递数据,它应该在数据库中

2.我尝试过:我试过传递查询请给出解决方案



嗯,没有多少工作环境;没有代码可以看出你的问题可能在哪里。

猜猜我们将从基础开始。



如何通过在C#WPF中将常量sting变量转换为SQL查询

执行此操作的正确方法是对要执行的命令使用参数化查询。

1.将命令文本创建为字符串,并使用aa 参数作为变量的占位符

string SqlCmdText =SELECT FNames FROM UserList WHERE EmailAddress = @Email;



然后在创建SqlCommand之后,将该参数添加到命令对象

cmd.Parameters.AddWithValue(@ Email,UserEmailAddress);



这是一个完整的您的样本

  public   static   string  GetFirstName( string  UserEmailAddress){

string ReturnValue = ;
string SqlConnString = {Connection String} ;
string SqlCmdText = SELECT FNames FROM UserList在哪里EmailAddress = @Email;

使用(SqlConnection conn = new SqlConnection(SqlConnString)){
使用(SqlCommand cmd = new SqlCommand(SqlCmdText,conn)){
cmd。 CommandType = CommandType.Text;
cmd.Parameters.AddWithValue( @ Email,UserEmailAddress);

conn.Open();

var sqlReturn = cmd.ExecuteScalar();
if (sqlReturn!= null ){ReturnValue = sqlReturn.ToString(); }

conn.Close();
}
}
return ReturnValue;
}





如果您有特定的查询或代码可供使用;我强烈建议您使用改善问题小部件并添加该代码。


基于现在提供的应用程序代码的附录

感谢您提供代码。

我们这里有几个问题:



1 。 SQL注入漏洞。切勿将字符串和输入值连接在一起以生成SQL语句。无论最终用户输入文本框,您都会受到影响。您可以通过在命令上下文中使用参数来避免这种情况。

我已经注释掉了问题的第一个实例,并将其替换为应该如何。您将需要执行类似于您使用的其他两个SQL命令

  //   cmd = new SqlCeCommand(SELECT * FROM Login where Where EmailID ='+ textEMail.Text +'and Password ='+ passwordBox1.Password +',conn);  
cmd = new SqlCeCommand( SELECT * FROM Login WHERE EmailID = @Email AND密码= @Password,conn);
cmd.Parameters.AddWithValue( @ Email,textEMail.Text);
cmd.Parameters.AddWithValue( @ Password,passwordBox1.Password);
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);



2。纯文本密码

绝对不能以明文形式存储密码。您应该实现一些散列的方法来保护它们。这需要的不仅仅是快速回答。我建议阅读这里和其他地方有关该主题的文章。我曾经使用过bCrypt的实现,并认为这也是可以接受的。

密码存储:怎么做。 [ ^ ]

使用BCrypt来填充你的密码:C#和SQL Server的示例«Rob Kraft的软件开发博客 [ ^ ]



这些要求合并所有凭据被盗

我需要做的就是使用这个电子邮件地址获取所有登录电子邮件和密码:

Fred'OR(1 = 1); -

这会将你的语句短路到SELECT * FROM Login,现在我要用每个人的明文密码来启动。


如此少的代码,如此多的严重错误......

永远不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。总是使用参数化查询。



连接字符串时会导致问题,因为SQL会收到如下命令:

  SELECT  *  FROM  MyTable  WHERE  StreetAddress = '  Baker' s Wood ' < span class =code-string>  

就SQL而言,用户添加的引号会终止字符串,并且您会遇到问题。但情况可能更糟。如果我来并改为输入:x'; DROP TABLE MyTable; - 然后SQL收到一个非常不同的命令:

  SELECT  *  FROM  MyTable  WHERE  StreetAddress = '  x';  DROP   MyTable;   -   ' 

哪个SQL看作三个单独的命令:

  SELECT  *  FROM  MyTable  WHERE  StreetAddress = '  x'; 

完全有效的SELECT

  DROP   TABLE  MyTable; 

完全有效的删除表格通讯和

   -   ' 

其他一切都是评论。

所以它确实:选择任何匹配的行,从数据库中删除表,并忽略其他任何内容。



所以总是使用参数化查询!或者准备好经常从备份中恢复数据库。您是否定期进行备份,不是吗?



切勿以明文形式存储密码 - 这是一个主要的安全风险。有关如何在此处执行此操作的信息:密码存储:如何做到这一点。 [ ^ ]



SqlConnection,SQLCommand等等都是稀缺资源:如果你创建它们,。你应该处理它们。最简单的方法是使用块在中创建它们,当它们超出范围时它们将自动处理。


< blockquote>

 cmd =  new  SqlCeCommand(  SELECT * FROM Login其中EmailID =' + textEMail.Text +  '和密码=' + passwordBox1.Password +  ',conn); 
字符串 q1 = 插入LoginTime( LoginDate,EmailID,Medium)值(getdate(),' + textEMail.Text + ', ' + Kannada.Text + ');



永远不要通过连接字符串来构建SQL查询。迟早,您将使用用户输入来执行此操作,这会打开一个名为SQL注入的漏洞,这对您的数据库很容易并且容易出错。

名称中的单引号你的程序崩溃。如果用户输入像Brian O'Conner这样的名称可能会使您的应用程序崩溃,那么这是一个SQL注入漏洞,崩溃是最少的问题,恶意用户输入,并且它被提升为具有所有凭据的SQL命令。

SQL注入 - 维基百科 [ ^ ]

SQL注入 [ ^ ]

按示例进行SQL注入攻击 [ ^ ]

PHP:SQL注入 - 手册 [ ^ ]

SQL注入预防备忘单 - OWASP [ ^ ]

我该怎么办?解释没有技术术语的SQL注入? - 信息安全堆栈交换 [ ^ ]


am not passing data and it should in database

What I have tried:

i have tried passing in queries please give the solution

here i need to enter paas constant string value like string English="English.Text" to the database

SqlCeConnection conn = new SqlCeConnection(DBConnection.GetConnString());

            SqlCeEngine engine = new SqlCeEngine(Common.CommonProperties.ConnString + Common.CommonProperties.Password);
            SqlCeCommand cmd;
            DataSet ds = new DataSet();
            if (textEMail.Text == "" || passwordBox1.Password == "")
            {
                System.Windows.MessageBox.Show(" Enter EmailID and Password .");
                return;
            }

            cmd = new SqlCeCommand("SELECT * FROM Login where EmailID='" + textEMail.Text + "' and Password='" + passwordBox1.Password + "'", conn);
            SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);

            da.Fill(ds);
            int i = ds.Tables[0].Rows.Count;
            if (i == 1)
            {
                conn.Open();
                String q1 = "insert into LoginTime(LoginDate,EmailID,Medium) values(getdate(),'" + textEMail.Text + "','" + Kannada.Text + "')";
                cmd.CommandType = CommandType.Text;

                cmd.CommandText = q1;
                cmd.ExecuteNonQuery();
                System.Windows.MessageBox.Show("You are Successfully Login ");

                Liststd_KM f2 = new Liststd_KM();
                f2.Show();
                this.Hide();
                //ds.Clear();

            }
            else
            {
                System.Windows.MessageBox.Show("Not Registered User or Invalid Name/Password");
                passwordBox1.Password = "";
            }

解决方案

How to pass constant sting variable into SQL query in C# WPF
1. am not passing data and it should in database
2. What I have tried: i have tried passing in queries please give the solution

Well, not much context to work with; and no code to see where your problems could be.
Guess we'll start with the basics.

How to pass constant sting variable into SQL query in C# WPF
The proper way to do this would be to use a parameterized query for the command you want to execute.
1. Create the command text as a string, and use a a parameter as the placeholder for the variable
string SqlCmdText = "SELECT FNames FROM UserList WHERE EmailAddress = @Email";

Then after your SqlCommand is created, you will add that parameter to the command object
cmd.Parameters.AddWithValue("@Email", UserEmailAddress);

Here is a full sample for you

public static string GetFirstName(string UserEmailAddress) {

  string ReturnValue = "";
  string SqlConnString = "{ Connection String }";
  string SqlCmdText = "SELECT FNames FROM UserList WHERE EmailAddress = @Email";

  using (SqlConnection conn = new SqlConnection(SqlConnString)) {
    using (SqlCommand cmd = new SqlCommand(SqlCmdText, conn)) {
      cmd.CommandType = CommandType.Text;
      cmd.Parameters.AddWithValue("@Email", UserEmailAddress);

      conn.Open();

      var sqlReturn = cmd.ExecuteScalar();
      if (sqlReturn != null) { ReturnValue = sqlReturn.ToString(); }

      conn.Close();
    }
  }
  return ReturnValue;
}



If you have a specific query or code to work with; I would highly suggest that you use the Improve Question widget and add that code in.


Addendum based on now-supplied application code
Thank you for supplying your code.
We have a few issues here:

1. SQL Injection Vulnerability. Never concantenate strings and input values together to make a SQL statement. You become susceptible to whatever an end-user enters into a text box. You can avoid this by using Parameters in the command context.
I have commented out the first instance of the problem and replaced it with how it should be. You will need to do similar to the two other SQL commands that you use

//cmd = new SqlCeCommand("SELECT * FROM Login where EmailID='" + textEMail.Text + "' and Password='" + passwordBox1.Password + "'", conn);
cmd = new SqlCeCommand("SELECT * FROM Login WHERE EmailID= @Email AND Password= @Password", conn);
cmd.Parameters.AddWithValue("@Email", textEMail.Text);
cmd.Parameters.AddWithValue("@Password", passwordBox1.Password);
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);


2. Plain-Text Passwords
You should never store passwords in plain-text. You should implement some method of hashing to protect them. This will require much more than a quick answer though. I would recommend reading the articles here and elsewhere on the topic. I have worked with implementations of bCrypt and would consider this acceptable as well.
Password Storage: How to do it.[^]
Use BCrypt to Hash Your Passwords: Example for C# and SQL Server « Rob Kraft's Software Development Blog[^]

Combined these are asking to have all credentials stolen
All I would need to do to get all of your login emails and passwords would be to use this email address:
Fred' OR (1=1);--.
This will short circuit your statement to "SELECT * FROM Login", and I now have everyone's plain-text passwords to boot.


So little code, so many serious errors...
Never 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. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:

SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'

The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:

SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'

Which SQL sees as three separate commands:

SELECT * FROM MyTable WHERE StreetAddress = 'x';

A perfectly valid SELECT

DROP TABLE MyTable;

A perfectly valid "delete the table" command

--'

And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

Never store passwords in clear text - it is a major security risk. There is some information on how to do it here: Password Storage: How to do it.[^]

SqlConnection, SQLCommand, and so forth are all scarce resources: if you create them,. you should Dispose them. The easiest way to do that is to create them in a using block, and they will automatically be Disposed when they go out of scope.


cmd = new SqlCeCommand("SELECT * FROM Login where EmailID='" + textEMail.Text + "' and Password='" + passwordBox1.Password + "'", conn);
String q1 = "insert into LoginTime(LoginDate,EmailID,Medium) values(getdate(),'" + textEMail.Text + "','" + Kannada.Text + "')";


Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability 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 a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
How can I explain SQL injection without technical jargon? - Information Security Stack Exchange[^]


这篇关于如何在C#WPF中将常量sting变量传递给SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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