Current im trying to use this im my code to try and read specific data between two different rows: example:
SELECT *
FROM chat
LIMIT 1, 20
In my c# code ive current got:
cmd.CommandText = "SELECT * from chat LIMIT " + cCfirst + "'" + cClast + "'";
Which isnt working in my code as the data reader isn't finding anything?
how can i fix this?
Try not constructing string from chunks which is prone to errors
// wrong technique, do not do it:
// 1. Can you see that "," is omitted?
// 2. Can you see that both "'" are at least redundant?
cmd.CommandText = "SELECT * from chat LIMIT " + cCfirst + "'" + cClast + "'";
but formatting eg with a help of string interpolation (C# 6.0+):
cmd.CommandText =
$@"SELECT *
FROM chat
LIMIT {cCfirst}, {cClast}";
Or in case of C# 5.0-
cmd.CommandText = string.Format(
@"SELECT *
FROM chat
LIMIT {0}, {1}",
cCfirst, cClast);
Make SQL being readable . Open SQL editor, debug the query, copy the query debugged into C# code, turn values into {...}
placeholders (eg 1
-> {cCfirst}
; 20
-> {cClast}
).
Then use the code:
using (MySqlConnection con = new MySqlConnection(YourCOnnectionString)) {
con.Open();
using (MySqlCommand cmd = new MySqlCommand()) {
cmd.Connection = con;
cmd.CommandText =
$@"SELECT *
FROM chat
LIMIT {cCfirst}, {cClast}";
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
//TODO: put relevant code here
}
}
}
}
The following illustrates the LIMIT clause syntax with two arguments:
SELECT
column1,column2,...
FROM
table
LIMIT offset , count;
In your C# code it seems you are missing comma between offset and count.
cmd.CommandText = "SELECT * from chat LIMIT " + cCfirst + "," + cClast;
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.