简体   繁体   中英

How to convert C# string to varchar PostgreSQL?

I have problem with types mismatch - I think. I have application which connects with database and sends query. That is how it works:

string wartosc1 = "'letters'";

NpgsqlCommand command9 = new NpgsqlCommand("SELECT * FROM RESOURCES WHERE TYPE = "+wartosc1, conn);

but when I try to execute it, there is answer:

System.FormatException: Input string was not in correct format.

I suppose that there is problem with type of variable because when I just input:

SELECT * FROM RESOURCES WHERE TYPE ='letters'

Everything is ok.

Any ideas?

You need to use parameters to pass in the value to the query.

Read http://msdn.microsoft.com/en-us/library/yy6y35y8(v=vs.110).aspx on how to do that.

var wartosc1 = "letters";

var command9 = new NpgsqlCommand("SELECT * FROM RESOURCES WHERE TYPE = @type", conn);
command9.Parameters.Add("@type", wartosc1);

Because when you write;

"SELECT * FROM RESOURCES WHERE TYPE = " + wartosc1

Your command will be like;

SELECT * FROM RESOURCES WHERE TYPE = letters

which is wrong because I suppose your TYPE column is some text type. If you solve this an easy way, you can add your wartosc1 variable inside single quotes like;

"SELECT * FROM RESOURCES WHERE TYPE = '" + wartosc1 + "'"

But please don't use this way.

You should always use parameterized queries in your commands. It prevents, forget to use some quotes, commas etc.. But more important this kind of string concatenations are open for SQL Injection attacks.

string wartosc1 = "letters";
NpgsqlCommand command9 = new NpgsqlCommand("SELECT * FROM RESOURCES WHERE TYPE = @type", conn);
command9.Parameters.AddWithValue("@type", wartosc1);

Here is an example of string Interpolation using several variables and a date:

var dt = DateTime.Now.AddDays(-30);
string wartosc1 = "letters";
string myStatement = $@"
    SELECT *
    FROM RESOURCES res
    WHERE res.DATE_EXAMPLE >= '{dt}' 
    AND res.TYPE = '{wartosc1}'
  "

BEWARE This sql string IS open to sql injection, simply by setting

wartosc1 = "somevalue' AND someOtherStatement 'thenDoSomethingBeforeApostrophe";

However, it may be that your environment doesn't need to worry about that... the apostrophes aren't necessary around an int, but forget it around a datetime, and you'll throw errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM