[英]C# - How do you use integers in c# to indentify the the limit to select from the table from mysql
當前的即時通訊正在嘗試使用此即時通訊我的代碼來嘗試讀取兩個不同行之間的特定數據:示例:
SELECT *
FROM chat
LIMIT 1, 20
在我的C#代碼中,IVE當前得到了:
cmd.CommandText = "SELECT * from chat LIMIT " + cCfirst + "'" + cClast + "'";
數據讀取器未找到任何內容,哪個在我的代碼中不起作用?
我怎樣才能解決這個問題?
嘗試不要從容易出錯的塊中構造字符串
// 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 + "'";
但是格式化,例如借助字符串插值 (C#6.0+):
cmd.CommandText =
$@"SELECT *
FROM chat
LIMIT {cCfirst}, {cClast}";
或使用C#5.0-
cmd.CommandText = string.Format(
@"SELECT *
FROM chat
LIMIT {0}, {1}",
cCfirst, cClast);
使SQL具有可讀性 。 打開SQL編輯器,調試查詢,將調試后的查詢復制到C#代碼中,將值轉換為{...}
占位符(例如1
> {cCfirst}
; 20
> {cClast}
)。
然后使用代碼:
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
}
}
}
}
下面說明了帶有兩個參數的LIMIT子句語法:
SELECT
column1,column2,...
FROM
table
LIMIT offset , count;
在您的C#代碼中,您似乎缺少了偏移量和計數之間的逗號。
cmd.CommandText = "SELECT * from chat LIMIT " + cCfirst + "," + cClast;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.