繁体   English   中英

C#-如何在C#中使用整数来确定要从mysql表中选择的限制

[英]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.

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