如何每秒执行一次SQL查询共5次并每次将结果输出到控制台
问题解决:SQL循环查询与类型转换错误处理
核心问题分析
你碰到的“无法在nvarchar与bigint之间转换”错误,根源是AddWithValue自动推断参数类型时出错——如果finalID格式类似数字,它会默认把参数类型设为bigint,但你的SQL中execution_id是nvarchar类型,导致类型不匹配。同时当前代码仅执行一次查询,未实现每秒执行一次、共5次的循环逻辑。
修正后的完整代码
if (File.Exists(filePath)) { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = strCmdText; startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; process.StartInfo = startInfo; process.Start(); string output = process.StandardOutput.ReadToEnd(); int first = output.IndexOf("ID:"); int last = output.IndexOf("To view"); string between = output.Substring(first + 4, last - first - 5); int FullStop = between.IndexOf("."); string finalID = between.Remove(FullStop, 1); Console.WriteLine("Import started..."); // 循环执行5次查询,每次间隔1秒 for (int i = 0; i < 5; i++) { // 使用using确保数据库资源自动释放 using (SqlConnection connection1 = new SqlConnection(connectionString)) { connection1.Open(); using (SqlCommand command = new SqlCommand(query, connection1)) { // 显式指定参数类型为nvarchar,避免自动推断错误 command.Parameters.Add("@execution_id", SqlDbType.NVarChar).Value = finalID; using (SqlDataReader sqlDataReader = command.ExecuteReader()) { // 读取单列结果 if (sqlDataReader.Read()) { string status = sqlDataReader.GetString(0); Console.WriteLine($"第{i+1}次查询结果: {status}"); } else { Console.WriteLine($"第{i+1}次查询无返回结果"); } } } } // 最后一次循环无需等待 if (i < 4) { System.Threading.Thread.Sleep(1000); } } Console.ReadKey(); } else { Console.WriteLine("No file found please try again"); Console.ReadKey(); }
关键修正说明
- 修复类型转换错误:弃用
AddWithValue,改用Add方法显式指定参数类型为SqlDbType.NVarChar,确保与SQL列类型完全匹配,避免自动推断导致的类型冲突。 - 实现循环逻辑:通过
for循环控制执行5次,每次循环后调用Thread.Sleep(1000)实现1秒间隔,最后一次循环跳过等待步骤。 - 资源安全管理:用
using语句包裹SqlConnection、SqlCommand和SqlDataReader,保证数据库资源自动释放,避免内存泄漏。 - 安全读取结果:直接使用
GetString(0)读取nvarchar类型列,比ToString()更直接且安全。
内容的提问来源于stack exchange,提问作者Lewis C
相关产品推荐
相关产品推荐

